Mankind1023
Mankind1023

Reputation: 7732

Custom RegEx expression for validating different possibilities of phone number entries?

I'm looking for a custom RegEx expression (that works!) to will validate common phone number with area code entries (no country code) such as:

111-111-1111

(111) 111-1111

(111)111-1111

111 111 1111

111.111.1111

1111111111

And combinations of these / anything else I may have forgotton.

Also, is it possible to have the RegEx expression itself reformat the entry? So take the 1111111111 and put it in 111-111-1111 format. The regex will most likely be entered in a Joomla / some type of CMS module, so I can't really add code to it aside from the expression itself.

Upvotes: 1

Views: 2100

Answers (3)

Tim Pietzcker
Tim Pietzcker

Reputation: 336418

\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})

will match all your examples; after a match, backreference 1 will contain the area code, backreference 2 and 3 will contain the phone number.

I hope you don't need to handle international phone numbers, too.

If the phone number is in a string by itself, you could also use

^\s*\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})\s*$

allowing for leading/trailing whitespace and nothing else.

Upvotes: 1

VeeArr
VeeArr

Reputation: 6178

Depending on the language in question, you might be better off using a replace-like statement to replace non-numeric characters: ()-/. with nothing, and then just check if what is left is a 10-digit number.

Upvotes: 0

John Gietzen
John Gietzen

Reputation: 49554

Why not just remove spaces, parenthesis, dashes, and periods, then check that it is a number of 10 digits?

Upvotes: 0

Related Questions