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.
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;
}
}
}