views:

115

answers:

4

Hi, 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.

A: 

Here's one:

.*

No, but seriously, this is a duplicate of http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation

disown
That one is more complex I think, it has international which I don't want, but also extensions, which I guess is something I forgot to consider but probably should at some point!
Murtez
A: 

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

John Gietzen
A: 

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
+1  A: 
\(?(\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