DEV Community

Olubunmi Alegbeleye
Olubunmi Alegbeleye

Posted on

Validating phone numbers using Google's libphonenumber library

What is libphonenumber?

Libphonenumber is Google’s library for parsing, formatting, and validating international phone numbers in Java, C++, and JavaScript. That sounds interesting. So, I can use this library to validate the phone numbers of any country.

Libphonenumber is a powerful library — it is a Swiss army knife. We will focus mostly on validating phone numbers with this library.

You can find the Github repo and documentation for the library here.

If you are collecting user phone numbers in your application and need to validate that they are correct, then read on.

Importing the library into an Android Project

To add libphonenumber to your Android Studio Project, add these to your project-level build.gradle file:

  1. Enable Maven Repository in your project if it has not yet been done:

    repositories {
      mavenCentral()
    }
    
  2. Add this line to your app-level build.gradle file to compile the dependencies:

    dependencies {
        ...
        implementation 'com.googlecode.libphonenumber:libphonenumber:8.2.0'
    }
    
  3. Rebuild your project so that Gradle can fetch the dependencies. After you have successfully built it, the library will be available for you to use in your app module.

Validating Nigerian Phone Numbers

Now that you have imported the library, let’s use it to validate Nigerian phone numbers.

Import the following in your java/android class:

import com.google.i18n.phonenumbers.PhoneNumberUtil
import com.google.i18n.phonenumbers.Phonenumber
Enter fullscreen mode Exit fullscreen mode

Create an instance of the PhoneNumberUtil class.

//Java
PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
Enter fullscreen mode Exit fullscreen mode
//Kotlin
private val phoneNumberUtil = PhoneNumberUtil.getInstance()
Enter fullscreen mode Exit fullscreen mode

This is the utility class for formatting, parsing, and validating international phone numbers. In case you like to read Javadocs, here is the link to the class’s Javadoc.

I know, just like me, you don’t, just follow along and I will show you how this works. “I gat you”.

This util class has a method isValidNumber() that returns true if the phone number matches a valid pattern and false otherwise:

//Java
public boolean isValidNumber(Phonenumber.PhoneNumber number)
Enter fullscreen mode Exit fullscreen mode
//Kotlin
fun isValidNumber(number: Phonenumber.PhoneNumber): Boolean
Enter fullscreen mode Exit fullscreen mode

Did I just read pattern and matching? Yes, you read right. Maybe that brings the dreaded regular expression to mind. Luckily for you and me, this util class and its functions replace all of that jargon. So, out with the regex.

The PhoneNumberUtil class also has a method isValidForRegion() that accepts region code in addition to isValidNumber()’s PhoneNumber parameter.

But where does this PhoneNumber.Number number parameter come from? The PhoneNumber class represents/stores a phone number. Javadoc people, here you go again.

Here is how you create an instance of the PhoneNumber class — a PhoneNumber object:

//Java
Phonenumber.PhoneNumber rawPhoneNumber = new Phonenumber.PhoneNumber();
Enter fullscreen mode Exit fullscreen mode
//Kotlin
val rawPhoneNumber = Phonenumber.PhoneNumber()
Enter fullscreen mode Exit fullscreen mode

Next, pass the country code and the national number you got from the user into the object you just created. Usually, you get these from two text fields or a drop-down menu and a text field in your user interface.

You have to parse the country code into an integer and the phone number into a long.

For Nigeria, the country code is “+234” or 234 in integer

and the national number is the user’s phone number in a format that can be dialled locally from Nigeria. That is the format: 080X XXX XXXX or 80X XXX XXXX.

At this point, all you need to do is set the two fields in the Phonenumber object you created, thus:

//Java
Phonenumber.PhoneNumber rawPhoneNumber = new Phonenumber.PhoneNumber();
rawPhoneNumber.setCountryCode(123);
rawPhoneNumber.setNationalNumber(123L);
Enter fullscreen mode Exit fullscreen mode
//Kotlin
val rawPhoneNumber = Phonenumber.PhoneNumber()
rawPhoneNumber.countryCode = countryCodeEditText.text.toString().toInt()
rawPhoneNumber.nationalNumber = phoneEditText.text.toString().toLong()
Enter fullscreen mode Exit fullscreen mode

To validate, pass this phone number object to the isValidNumber() function you came across earlier:

//Java
Phonenumber.PhoneNumber rawPhoneNumber = new Phonenumber.PhoneNumber();
rawPhoneNumber.setCountryCode(123);
rawPhoneNumber.setNationalNumber(123L);
boolean isValidNumber = phoneNumberUtil.isValidNumber(rawPhoneNumber);
Enter fullscreen mode Exit fullscreen mode
//Kotlin
val rawPhoneNumber = Phonenumber.PhoneNumber()
rawPhoneNumber.countryCode = countryCodeEditText.text.toString().toInt()
rawPhoneNumber.nationalNumber = phoneEditText.text.toString().toLong()
val isValid = phoneNumberUtil.isValidNumber(rawPhoneNumber)
Enter fullscreen mode Exit fullscreen mode

To save user details on your server, you can pass both components of the phone number you have collected and validated as a JSON object:

{
  "userPhoneNumber" : {
    "country_code": 234,
    "national_number": 8012345678
  }
}
Enter fullscreen mode Exit fullscreen mode

Or you may want to send it to your server in the international form. For example +23490X XXX XXXX for Nigeria. There is information on how to get the validated phone number in the international format in the sidebar.

In this short article, we saw in action a powerful library that replaces all those ugly regular expressions when validating phone numbers.


Sidebar: Parsing and Formatting phone numbers with libphonenumber

Formatting Phone Numbers

You may need to format the validated phone number in a different format. That is where the PhoneNumberUtil’s formatting ability comes in. Just do this. In this example, we format the phone number as an E.164 number:

//Java
String internationalFormat = phoneNumberUtil.format(rawPhoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
Enter fullscreen mode Exit fullscreen mode
//Kotlin
internationalFormat = phoneNumberUtil.format(rawPhoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164)
Enter fullscreen mode Exit fullscreen mode

Don’t be confused with that second parameter. They are constants in the util class that represents different phone number formats: E164, INTERNATIONAL, NATIONAL, and RFC3966.

So, you’re just telling PhoneNumberUtil in what format you want your output.

Parsing Phone Numbers

Let’s briefly learn about parsing phone numbers with PhoneNumberUtil.

If you have your phone number in any format (E164, national, international, etc), even if the phone number is embedded in a string, just invoke the parse function like this:

//Java
Phonenumber.PhoneNumber parsedPhoneNumber = phoneNumberUtil.parse(CharSequence numberToParse, String regionCode);
Enter fullscreen mode Exit fullscreen mode
//Kotlin
val parsedPhoneNumber = PhoneNumberUtil.parse(numberToParse: CharSequence, regionCode: String)
Enter fullscreen mode Exit fullscreen mode

The region code identifies what region the number is expected to be from. That’s NG for Nigeria. And kaboom!, you have phoneNumber in PhonenNumber.PhoneNumber form.

The country code and the national number have been parsed into individual fields like this:

{
  "country_code": 234,
  "national_number": 8012345678
}
Enter fullscreen mode Exit fullscreen mode

Here is a warning!!!

If you pass a string that cannot be parsed into PhoneNumberUtil.parse(), say because it doesn’t contain a valid phone number, a NumberParseException is thrown. Usually, we surround things like this in try-catch blocks, but the ball (or the exception in this case) is in your court.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.