Possible Duplicate:
US Phone Number Verification
I need to validate US phone number. It could be in the format:
xxx-xxx-xxxx
(xxx) xxx xxxx
(xxx)-xxx-xxxx
xxxxxxxxxx
but it should not be
xxx-xxx-xxxx-
-xxx-xxx-xxxx
It should accept digits, hyphens, space and parentheses.
Currently I use
^\[0-9 \-\. ]+$
which does not validate dash at the beginning or end.
^\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}$
Well my idea is (after some searching) not new at all! Look at this:
A comprehensive regex for phone number validation
This is an Excellent suggestion btw.
This one is probably correct (assuming some parsing errors depending on the regex engine you are using. It's also ugly as hell :(.
(?:\d{3}(?:\d{7}|\-\d{3}\-\d{4}))|(?:\(\d{3}\)(?:\-\d{3}\-)|(?: \d{3} )\d{4})
(^\(?[0-9]{3}\)?\-?\s?[0-9]{3}\-?\s?[0-9]{4}[^-])
I tested this on http://regexhero.net/tester/ and got it to select the following patterns:
xxx-xxx-xxxx
(xxx) xxx xxxx
(xxx)-xxx-xxxx
xxxxxxxxxx
It ignored the following patterns:
xxx-xxx-xxxx-
-xxx-xxx-xxxx
I hope this helps, or at least moves you in the correct direction.
This should do the trick:
/^([\d]{6}|((\([\d]{3}\)|[\d]{3})( [\d]{3} |-[\d]{3}-)))[\d]{4}$/
- It starts by checking if the first 6 digits are
xxxxxx
, - if not it looks if the first three digits are
(xxx)
or justxxx
- and if one of those it checks if the next three are
xxx
or-xxx-
- and if one of those it checks if the next three are
- At the end it checks that there are four trailing digits
xxxx
来源:https://stackoverflow.com/questions/12101125/regex-to-allow-only-digits-hypens-space-parentheses-and-should-end-with-a-dig