zParacha.com

Effective programming and blogging tips by Zaheer Paracha

Subscribe:

-->
Posted by Zaheer 3 COMMENTS
279804967 668397cde9 m Validate U.S Phone Numbers using JavaScript Regular expression.
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.

Bookmark and Share

Popularity: 19% [?]

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

Related posts:

categories: Javascript

3 Responses

  1. suresh says:

    Hi,
    Ur javaacript for validating controls is very clear.and easy.

    thank u

  2. Abel Curtice says:

    Very intereresting reading. thx

  3. vertaa vippi says:

    Vertaa pikalainaaan päätös lainojen saada paras käsitellä – Kun verrataan lainat varmista voit pohtia huolellisesti todellinen vuosikorko sekä tsekkamall piilomaksuja.

Leave a Reply

Search

Sponsors

Get Adobe Flash playerPlugin by wpburn.com wordpress themes