Email This Post
Print This Post
Validate Phone Number
Thu, Oct 18, 2007 – 1:33 pmSimple Phone number validation function that returns “true” if the phone number is in the format 555-555-5555
Useful when validating input from a form prior to writing it to a database.
(Note the use of regular expressions used to validate the formatting)
/**
* This function validates that the provided string is a phone number with
* the format of 555-555-5555
*
* @param s the String containing the phone number
* @return boolean
*/
function isValidPhoneNumber(s) {
// See if it is empty
if (s.length == 0) {
alert("Please enter a value for the phone number.");
return false;
}
// Make Regular expression for checking for correct phone number format
rePhoneNumber = new RegExp(/^[1-9]\d{2}\-\d{3}\-\d{4}$/);
// Test string using regular expression (return false if it fails)
if (!rePhoneNumber.test(s)) {
alert("Phone Number Must Be Entered As: 555-555-5555");
return false;
}
return true;
}