简体   繁体   中英

Validate us number with regular expression

I'm doing an exercise on freecodecamp for validate us telephone number.

The user may fill out the form field any way they choose as long as it is a valid US number. The following are all valid formats for US numbers:

555-555-5555, (555)555-5555, (555) 555-5555, 555 555 5555, 5555555555, 1 555 555 5555

I'm using RegEx to test input.I type these expression on regex101

(([1]\s)?(\()*(\d{3})(-|\)|\)\s|\s)*(\d{3})(-|\s)*\d{4})

to test input like:

2 ** (757) 622-7382** return true

- 1 (757) 622-7382 return true

10 ** (757) 622-7382** return true

How could I test the leading 2, minus sign and 10.

I would suggest you to have a look on OWASP Validation Regex Repository as they are subject of validation and continuous updates

For the US Phone (at the time I'm writing)the suggested RegEx is ^\\D?(\\d{3})\\D?\\D?(\\d{3})\\D?(\\d{4})$

((-)?\\d{0,2} )? Notice the space after {0,2}

(-)?       // may begin with a minus
(\d{1,2})?   // may have 1 or 2 digits before the actual number
( )?       // may have a space after that

DEMO

Here is a modified version of your regex that will now match the new phone formats:

^[-+]?(?:\d{1,2}\s)?\(*(?:\d{3})(?:-|\)|\)\s|\s)*\d{3}(?:-|\s)*\d{4}$

See demo

Note I removed the capture groups (I doubt you need them, and they create additional overhead) and added optional + or - before the number. Also, \\d{1,2} matches 1 or 2 digits due to the limiting quantifier {1,2} .

Might be a bit late but here is the solution to this one.

/^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\s\-]?\d{4}$/;

You do want to have the ^ at the beginning of the expression to match the first char of the string and you want to use $ at the end to let the expression know that this is the end.

You can see the above answer and another way of doing it on the following github github link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM