The (almost) Perfect Phone Regex

While working on an inline form validation feature for A6X, I needed to be able to validate phone numbers. The phone regex with the plugin I was using was crappy and didn’t allow you to enter things such as an extension, or use (###) for the area code. Every validation plugin I used had, in my opinion, bad regex, which only took into account a small fraction of ways to type a phone number.

I wanted to be able to do things like:

  • Use (###) format for the area code
  • Add a +1 for a country code
  • Use . instead of –
  • Add an extension, etc

Yet for some reason, literally no regex that I found would allow for this in its entirety. So, obviously, I handcrafted my own.

This allows you to enter phone numbers in many different formats:

  • +1 is entirely optional, but still allowable
  • You can enter the area code with or without surrounding parentheses (###)
  • Numbers can be spaced with spaces, a . or a – (or nothing) – such as 123-4567, 123.4567, 123 4567
  • You can optionally enter an extension
    • Allowable formats: “ex”, “ext”, “extension” followed by a space, a . or a – (or nothing) and then some numbers

The only reason I say it’s “almost” perfect is because while loosely designed around US numbers, it may/may not validate for other countries. Any country with seven digit numbers should theoretically validate. And of course, there’s probably the case where someone wants to enter a weird character like a tilde (~) or something, which isn’t supported.

Regardless, though, I think this is the most effective regex for a phone number I’ve seen on the internet.

,

3 responses to “The (almost) Perfect Phone Regex”

  1. I would write some test cases in a separate file with the RegExp so that people can see how and what it validates with.


    1. That’s a really good idea. It also gives me the opportunity to decide where I want to store my test files on the server.



Leave a Reply

Your email address will not be published. Required fields are marked *