The regular expression only allows numbers, hypens, space, parentheses and must end with a number (javascript)

Possible duplicate:
Checking your U.S. phone number

I need to check the phone number in the USA. It can 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 must accept numbers, hyphens, spaces, and parentheses.

I am currently using

 ^\[0-9 \-\. ]+$ 

which does not confirm a dash at the beginning or end.

+4
source share
5 answers
 ^\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}$ 
+4
source

Well, my idea (after some searching) is not new at all! Look at this:

Full regex to verify phone number

This is a great suggestion by the way.

+2
source

This is probably correct (assuming some parsing errors depend on the regular expression engine you are using, and also ugly: (.

 (?:\d{3}(?:\d{7}|\-\d{3}\-\d{4}))|(?:\(\d{3}\)(?:\-\d{3}\-)|(?: \d{3} )\d{4}) 
+1
source

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 it doesn’t look, if the first three digits (xxx) or just xxx
    • and if one of them checks if the next three will be xxx or -xxx-
  • In the end, he checks that there are four lagging digits xxxx
0
source
 (^\(?[0-9]{3}\)?\-?\s?[0-9]{3}\-?\s?[0-9]{4}[^-]) 

I tested this at http://regexhero.net/tester/ and got it to select the following templates:

 xxx-xxx-xxxx (xxx) xxx xxxx (xxx)-xxx-xxxx xxxxxxxxxx 

He ignored the following patterns:

 xxx-xxx-xxxx- -xxx-xxx-xxxx 

I hope this helps, or at least moves you in the right direction.

0
source

All Articles