JavaScript City

Phone Number Validation

This script that allows you to validate a standard 10-digit phone number. Choose whether to validate using all numbers, -, or spaces.

Script Code

Grab a copy of the file below and place it in the same directory as the Web page on which you will use the script (if you wish to place the script file in a different directory you will need to make the necessary adjustments to the src attribute of the script tag that calls it).

sval001.js

The code below should be placed between the <body> and </body> tags where you want the phone number field to appear.

Example

A working sample of the script is shown below.

  

Options

You can change the appearance of the input box and the button by adding the phone_number id and sub_ph id to your style sheet and editing as desired.

Be sure to set the url of the form's action attribute in the HTML code to reflect your form handling script on your server:

<form action="form_script_url" onsubmit="return check_phone_number();">

You can choose how the viewer should format the phone number by editing the num_division variable in the javascript code (instructions in code comments):

/* Set whether the user should use a -, a space, or one long number without divisions.
   Use the following values to set:
   1 = Use - (i.e 123-456-7890)
   2 = Use a space (i.e. 123 456 7890)
   3 = Use none (i.e. 1234567890)
*/
var num_division = 3;

Accessibility

A backup to the script via a server-side script that validates the phone number should suffice (and is highly recommended for security reasons to avoid bad data being passed).


eXTReMe Tracker