Back to Blog
ValidationRegexJavaScript

Stop Using Bad Regex for Phone Validation: A Guide to E.164

D
DevData Team
Oct 24, 2023
5 min read
ADVERTISEMENT
Google AdSense Space (auto)

As developers, we've all been there. You need to validate a phone number field, so you Google "phone number regex" and copy the first StackOverflow answer with 500 upvotes from 2012.

Big mistake.

The Problem with Simple Regex

Most basic regex patterns assume US-centric formats like (555) 123-4567. They fail spectacularly when users enter:

  • Numbers with spaces: +44 7700 900000
  • Numbers with dots: 555.123.4567
  • International codes without delimiters: +8613912345678

Enter E.164: The Gold Standard

E.164 is the international standard for public telecommunication numbering plans. The logic is simple:

[+] [Country Code] [Subscriber Number]

It can contain up to 15 digits. It does not contain spaces, dashes, or parentheses when stored in a database. This is why our DevDataPhone Generator defaults to this clean format.

The Solution

Instead of restricting user input on the frontend to strict formats, you should:

  1. Allow users to input numbers with loose formatting (spaces, dashes).
  2. Strip all non-numeric characters (except the leading +).
  3. Validate the length and country code against a library like libphonenumber-js or our regex patterns provided on the home page.
  4. Save to your database in E.164 format.

Check out our Regex section to get compliant patterns for the US, UK, China, and more.

ADVERTISEMENT
Google AdSense Space (auto)