Ravikumar Sharma
Ravikumar Sharma

Reputation: 3740

RegEx for validating US phone number format

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.

Upvotes: 0

Views: 8422

Answers (2)

Sukhjinder Singh
Sukhjinder Singh

Reputation: 1825

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

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26667

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

Upvotes: 2

Related Questions