DEV Community

Adil BEK
Adil BEK

Posted on

Validating phone numbers: a developers primer

For developers, validating phone numbers is just another form of validation, like dates and emails, until you try actually validating an international phone number, then you find out its a real pain in the butt!

International numbers dont follow any pattern. Each country has its own numbering plan with different number of digits. What makes matters worst is that in most coutries, not all numbers ranges are in use. So its easy to accept non-existing numbers even if you validate the pattern (using a regex for example).

The good news is that Google already did the heavy lifting for us. They compiled all the international patterns into one awesome library called libphonenumber.

That being said, there are basically two ways to validate international phone numbers:

  1. By embedding Google's library in your own code
  2. Using an API which will itself use libphonenumber or other more advanced validations

If you choose the first method make sure to update the library with every new release. If you go for API's, this page [https://veriphone.io/docs/code-example] has an extensive list of code examples (Diclaimer: I work for Veriphone)

Conclusion: no regex nor any piece of magic code you can come up with will validate phone numbers effectively. Stop trying implementing your own and use either Google's library or an API.

Top comments (0)