Photo credit: aussiegall

Continuing with our JavaScript regular expression series today we will discuss JavaScript regular expression to validate U.S phone number. Previously we talked about validating email , Social Security number and zip code using JS regex.

In today’s post I’ll show you how to use JavaScript regular expression to validate U.S phone number.


Although in this article we are discussing U.S phone number format I am sure this can be applied to other phone number formats with little or no change.

Let’s begin by looking at the JavaScript code.


function validatePhoneNumber(elementValue){
var phoneNumberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
return phoneNumberPattern.test(elementValue);
}

Explanation:

The argument to this method is the phone number you want to validate.

In the method body we define a variable (‘phoneNumberPattern’) and assign a regular expression to it.

Phone Number format: The regular expression for phone number is

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

Let’s divide this regular expression in smaller fragments to make is easy to understand.


/^\(?
: Means that the phone number may begin with an optional “(“.


(\d{3})
: After the optional “(” there must be 3 numeric digits. If the phone number does not have a “(“, it must start with 3 digits. E.g. (308 or 308.

\)?: Means that the phone number can have an optional “)” after first 3 digits.

[- ]?: Next the phone number can have an optional hyphen (“-“) after “)” if present or after first 3 digits.

(\d{3}): Then there must be 3 more numeric digits. E.g (308)-135 or 308-135 or 308135

[- ]?: After the second set of 3 digits the phone number can have another optional hyphen (“-“). E.g (308)-135- or 308-135- or 308135-

(\d{4})$/: Finally, the phone number must end with four digits. E.g (308)-135-7895 or 308-135-7895 or 308135-7895 or 3081357895.


On the final line we call test method for our regular expression and pass the phone number as input. If the input phone number satisfies our regular expression, ‘test’ will return true otherwise it will return false. We return this value to the calling method.


If you enjoyed this post, make sure you subscribe to my RSS feed!