开发者

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

开发者 https://www.devze.com 2023-01-03 05:05 出处:网络
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:

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 mos开发者_StackOverflow社区t 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.


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消