HOME  |  AJAX  |  SOLUTIONS  |  TECHNOLOGIES  |  E-COMMERCE  |  ABOUT US  |  JOBS
Validating Phone Numbers - JavaScript

Validating a 10 Digit Phone Number with JavaScript

Test form - Enter any valid 10 digit phone number in any format.

This code validates a 10 digit phone number taken in any format and sets the phone number text field to the desired output format. The idea behind this code is to make it as simple as possible for the user to correctly enter their phone number in the correct format.

Download the HTML Source File

Why another validation scheme?

There are a million different implementations on the web for validating a phone number.  Most of these require the user to enter their phone number in an exact format defined by the programmer.  Why shouldn't the user be able to enter their phone number in any valid format?  Computers are very good at parsing text, and it's our duty as programmers to make form validation a usability improvement rather than an obstacle.

How it works

Basically our validatePhone function takes an HTML text input field and a format type, strips all non-digits from the number and validates based on the cleansed string lenght.

This would need to be updated for international numbers, or to allow users to enter phone numbers using letter representation.

In a real case, this function would probably be called as part of a larger validate form function. If the phone number was invalid, we would want to return false to cancel form submission as well as informing the user of the errors of their ways.

To improve usability, we could call this function from the phone number input field's onblur() event. This way after the user tabbed away from the textbox, their number would automatically be formatted.

//Validate phone number for 10 digit US numbers.

//phoneField - The HTML input field containing the phone number to validate.

//format - Integer value that defines how to format the text field.

function validatePhone(phoneField, format) {

   var num = phoneField.value.replace(/[^\d]/g,'');

   if(num.length != 10) {

        //Alert the user that the phone number entered was invalid.

        alert('Please enter a valid phone number including area code');                   

   } else {

        //Email was valid.  If format type is set, format the Phone to the desired style.

      switch(format) {

            case '0': //Format (xxx)-xxx-xxxx

               phoneField.value = "(" + num.substring(0,3) + ")-" +

                                    num.substring(3, 6) + "-" + num.substring(6);

               break;

            case '1': //Format xxx-xxx-xxxx

               phoneField.value = num.substring(0,3) + "-" +

                                    num.substring(3, 6) + "-" + num.substring(6);

               break;

            default: //Format xxxxxxxxxx

               phoneField.value = num;

               break;

        }

   }

}