1

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.

Mankind1023
  • 7,198
  • 16
  • 56
  • 86
  • possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – John Gietzen Jun 08 '10 at 14:26

3 Answers3

1
\(?(\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.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

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

John Gietzen
  • 48,783
  • 32
  • 145
  • 190
0

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.

VeeArr
  • 6,039
  • 3
  • 24
  • 45