Home > Software design >  RegExp for phone number that allows extension abbreviation
RegExp for phone number that allows extension abbreviation

Time:10-24

I'm very beginner with regExp. I'm creating a form that allows users to input a 7/10 digit number which auto formats.

I now need to add in a possible extension. My current validation uses

export const regXPhoneNumber = /^(?:\d{3}|\(\d{3}\))([-/.])\d{3}\1\d{4}$/i;

What would I need to add to this regX to allow for a format like this.

123-456-789 ext. 889

I currently have a function where after detecting 10 digits, it automatically adds ext. to the end and the user only has to enter the extension digits.

where the value after the ext. can be anywhere from 1-5 digits?

Thanks

CodePudding user response:

I would suggest the following regex pattern:

^\d{3}(?:[-.]\d{3})?[-.]\d{4}(?: ext\. \d{1,5})?$

This says to match:

  • ^ from the start of the number
  • \d{3} mandatory leading three digits
  • (?:[-.]\d{3})? optional three digit exchange
  • [-.] hyphen or dot separator
  • \d{4} final four digits
  • (?: ext\. \d{1,5})? optional "ext. 12345" portion
  • $ end of the number

Here is a working demo.

  • Related