June 15, 2008

Validation checks if the phone number is valid

The function below checks if the phone number is valid. At first we use regular expression and the replace() method to clear out any spacer characters. Next, we use the isNaN() function to check if the phone number contain only numbers. At last we check the length of the string and permit only phone numbers with 10 digits.

function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');

if (fld.value == "") {
error = "You didn't enter a phone number.\n";
fld.style.background = 'Yellow';
} else if (isNaN(parseInt(stripped))) {
error = "The phone number contains illegal characters.\n";
fld.style.background = 'Yellow';
} else if (!(stripped.length == 10)) {
error = "The phone number is the wrong length. Make sure you included an area code.\n";
fld.style.background = 'Yellow';
}
return error;
}

Subscribe to

Add to Google
Add to My Yahoo!
Subscribe Via Web Feed
kick it on DotNetKicks.com