0

I searched for phone number validation and ended up with below javascript code

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
      phone_number = phone_number.replace(/\s+/g, "");
      return this.optional(element) || phone_number.length > 9 &&
               phone_number.match(/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/);
}, "");

The above code will return true for below formats

123-123-1234 or (123) 123-1234 or 1231231234

Nw I need to add extension for number for eg

123-123-1234 x1234

(123) 123-1234 x1234

1231231234 x1234

I tried with all my experience with regex (much little :) ) but didn't worked :(

Can you change in my regex to validate x1234

Thanks.

Ravikumar Sharma
  • 3,528
  • 4
  • 32
  • 53

2 Answers2

2

You can add an optional match at the end of the regex

( x\d{4})? 

Which will match x followed by digits, that is eg x1234 if it is present

  • ( x\d{4})? the quantifier ? matches zero or one occurence of ( x\d{4})

The regex can be

^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})( x\d{4})?$

For example : http://regex101.com/r/sG9qJ6/1

nu11p01n73R
  • 25,677
  • 2
  • 36
  • 50
0

I think this question is already asked with answer as well. Check this A comprehensive regex for phone number validation

Community
  • 1
  • 1
Sukhjinder Singh
  • 1,525
  • 2
  • 17
  • 25