Stop Using Bad Regex for Phone Validation: A Guide to E.164
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:
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:
- Allow users to input numbers with loose formatting (spaces, dashes).
- Strip all non-numeric characters (except the leading +).
- Validate the length and country code against a library like
libphonenumber-jsor our regex patterns provided on the home page. - Save to your database in E.164 format.
Check out our Regex section to get compliant patterns for the US, UK, China, and more.