Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we'll see how to use Google's open-source library libphonenumber to validate phone numbers in Java.

2. Maven Dependency

First, we'll need to add the dependency for this library in our pom.xml:

<dependency>
    <groupId>com.googlecode.libphonenumber</groupId>
    <artifactId>libphonenumber</artifactId>
    <version>8.12.10</version>
</dependency>

The latest version information can be found over on Maven Central.

Now, we're equipped to use all the functionality this library has to offer.

3. PhoneNumberUtil

The library provides a utility class, PhoneNumberUtil, which provides several methods to play around with phone numbers.

Let's see a few examples of how we can use its various APIs for validation.

Importantly, in all examples, we'll be using the singleton object of this class to make method calls:

PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();

3.1. isPossibleNumber

Using PhoneNumberUtil#isPossibleNumber, we can check if a given number is possible for a particular country code or region.

As an example, let's take the United States, which has a country code of 1. We can check if given phone numbers are possible US numbers in this fashion:

@Test
public void givenPhoneNumber_whenPossible_thenValid() {
    PhoneNumber number = new PhoneNumber();
    number.setCountryCode(1).setNationalNumber(123000L);
    assertFalse(phoneNumberUtil.isPossibleNumber(number));
    assertFalse(phoneNumberUtil.isPossibleNumber("+1 343 253 00000", "US"));
    assertFalse(phoneNumberUtil.isPossibleNumber("(343) 253-00000", "US"));
    assertFalse(phoneNumberUtil.isPossibleNumber("dial p for pizza", "US"));
    assertFalse(phoneNumberUtil.isPossibleNumber("123-000", "US"));
}

Here, we used another variant of this function as well by passing in the region that we're expecting the number to be dialed from as a String.

3.2. isPossibleNumberForType

The library recognizes different types of phone numbers, such as fixed-line, mobile, toll-free, voicemail, VoIP, pager, and many more.

Its utility method isPossibleNumberForType checks if the given number is possible for a given type in a particular region.

As an example, let's go for Argentina since it allows for different possible lengths of numbers for different types.

Hence, we can use it to demonstrate the capability of this API:

@Test
public void givenPhoneNumber_whenPossibleForType_thenValid() {
    PhoneNumber number = new PhoneNumber();
    number.setCountryCode(54);

    number.setNationalNumber(123456);
    assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
    assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));

    number.setNationalNumber(12345678901L);
    assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.FIXED_LINE));
    assertTrue(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.MOBILE));
    assertFalse(phoneNumberUtil.isPossibleNumberForType(number, PhoneNumberType.TOLL_FREE));
}

As we can see, the above code validates that Argentina permits 6-digit fixed line numbers and 11-digit mobile numbers.

3.3. isAlphaNumber

This method is used to verify if the given phone number is a valid alphanumeric one, such as 325-CARS:

@Test
public void givenPhoneNumber_whenAlphaNumber_thenValid() {
    assertTrue(phoneNumberUtil.isAlphaNumber("325-CARS"));
    assertTrue(phoneNumberUtil.isAlphaNumber("0800 REPAIR"));
    assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE"));
    assertTrue(phoneNumberUtil.isAlphaNumber("1-800-MY-APPLE.."));
    assertFalse(phoneNumberUtil.isAlphaNumber("+876 1234-1234"));
}

To clarify, a valid alpha number contains at least three digits at the beginning, followed by three or more alphabet letters. The utility method above first strips the given input off any formatting and then checks for this condition.

3.4. isValidNumber

The previous API we discussed quickly checks the phone number on the basis of its length only. On the other hand, isValidNumber does a complete validation using prefix as well as length information:

@Test
public void givenPhoneNumber_whenValid_thenOK() throws Exception {

    PhoneNumber phone = phoneNumberUtil.parse("+911234567890", 
      CountryCodeSource.UNSPECIFIED.name());

    assertTrue(phoneNumberUtil.isValidNumber(phone));
    assertTrue(phoneNumberUtil.isValidNumberForRegion(phone, "IN"));
    assertFalse(phoneNumberUtil.isValidNumberForRegion(phone, "US"));
    assertTrue(phoneNumberUtil.isValidNumber(phoneNumberUtil.getExampleNumber("IN")));
}

Here, the number is validated when we did not specify a region, and also when we did.

3.5. isNumberGeographical​

This method checks if a given number has geography or region associated with it:

@Test
public void givenPhoneNumber_whenNumberGeographical_thenValid() throws NumberParseException {
    
    PhoneNumber phone = phoneNumberUtil.parse("+911234567890", "IN");
    assertTrue(phoneNumberUtil.isNumberGeographical(phone));

    phone = new PhoneNumber().setCountryCode(1).setNationalNumber(2530000L);
    assertFalse(phoneNumberUtil.isNumberGeographical(phone));

    phone = new PhoneNumber().setCountryCode(800).setNationalNumber(12345678L);
    assertFalse(phoneNumberUtil.isNumberGeographical(phone));
}

Here, in the first assert above, we gave the phone number in an international format with the region code, and the method returned true. The second assert uses a local number from the USA, and the third one a toll-free number. So the API returned false for these two.

4. Conclusion

In this tutorial, we saw some of the functionality offered by libphonenumber to format and validate phone numbers using code samples.

This is a rich library that offers many more utility functions and takes care of most of our application needs for formatting, parsing, and validating phone numbers.

As always, the source code is available over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
guest
0 Comments
Inline Feedbacks
View all comments