0

I am trying to build a javascript regex for phone number.

I currently have this...but it is failing.

^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})?[#. ]?([0-9]{10})$

Examples:

(555) 555-1212 - Acceptable 
(555) 555-1212 #12525 - Acceptable (Up to 10 digits after the # sign)
5555551212 - Acceptable
555-555-1212 - Acceptable
555-555-1212 #12525 - Acceptable (Up to 10 digits after the # sign)

Any alpha characters should be Unacceptable

(555) 555-1212 ext 12525 - Unacceptable
(555) 555-1212 x12525 - Unacceptable

Regex has been a weak area of mine and I am not sure how to make it work.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
jlimited
  • 685
  • 2
  • 11
  • 20
  • 4
    Does this answer your question? [How to validate phone numbers using regex](https://stackoverflow.com/questions/123559/how-to-validate-phone-numbers-using-regex) – pilchard Dec 30 '20 at 22:34

2 Answers2

0

You can use

^\(?([0-9]{3})\)?[-. ]?([0-9]{3})(?:[-. ]?([0-9]{4}))?(?:[#. ]+([0-9]{1,10}))?$

See the regex demo.

Main points are: 1) turning [#. ]? into [#. ]* because there can be both spaces and # (or maybe ., too) before the coming digits, and 2) [0-9]{10} turning into [0-9]{1,10} to match one to ten digits.

Details

  • ^ - start of string
  • \(? - an optional (
  • ([0-9]{3}) - Group 1: three digits
  • \)? - an optional )
  • [-. ]? - an optional delimiter
  • ([0-9]{3}) - Group 2: three digits
  • (?:[-. ]?([0-9]{4}))? - an optional sequence of an optional delimiter and four digits captured into Group 3
  • (?:[#. ]+([0-9]{1,10}))? - an optional sequence of one or more delimiters and then one to ten digits captured into Group 4
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

This will match all of your test cases, but it can still fail if any of them are mixed.

\(?\d{3}\)?[\- ]?\d{3}[\-]?\d{4}( #\d{1,10})?

Your best bet would be to make a separate regex for each format you want to accept and then test the string against all of them to see if any match.

I recommend using a regex tester to see your query match in real time.

https://regex101.com/

John
  • 5,942
  • 3
  • 42
  • 79