How does Google’s i18n Phone Number Validation Library Work?

Short details to understand how phone number validation is performed with googlei18n libphonenumber dependency

Photo by Miryam León on Unsplash

For phone number validation, since regex does not cover all cases for all countries, Google’s PhoneNumberUtil is preferred to be used (https://github.com/googlei18n/libphonenumber).

For the first 3 characters, first one or first two or first three, is checked against countryCallingCodeToRegionCodeMap and the first found match is selected as countryCode. If a countryCode cannot be found, an exception will be thrown:

countryCallingCodeToRegionCodeMap content (there have been updates since my last debug inspect but still will look more or less alike):

After a countryCode is selected, it gets the countryCode’s mapping region list for countryCallingCodeToRegionCodeMap.

There is also a phoneNumberRegion which distinguishes the actual country.

For example, for Barbados, countryCode=1 and regionCode=246

After that, the phone number you provided is ready to be applied a pattern regex for each of the regex values in metadata xml file given for countryCode.

The main methods that perform these are pasted below:

The main method definition:

Method which finds countryCode (MAX_LENGTH_COUNTRY_CODE = 3 as static default):

Method which finds regionCode:

You can see the original methods here:

You can also check how it works with the demo https://libphonenumber.appspot.com/

https://libphonenumber.appspot.com/

I searched online for a public library phone to check: +44 (0)1937 546546 https://www.bl.uk/about-us/contact-us#

Now, I will be testing for this number. I only filled in input field in Step 1 (removed parenthesis and empty spaces) and then hit Submit button:

Result Page:

Here is a small Utility Class to show how you can use the dependency for phone number validation in Java:

Happy Coding!

--

--

I would love to change the world, but they won’t give me the source code | coding 👩🏼‍💻 | coffee ☕️ | jazz 🎷 | anime 🐲 | books 📚 | drawing 🎨

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nil Seri

I would love to change the world, but they won’t give me the source code | coding 👩🏼‍💻 | coffee ☕️ | jazz 🎷 | anime 🐲 | books 📚 | drawing 🎨