
click to enlarge
When you ask a user for a telephone number you expect a few things. That the telephone number is 10 digits long for those in USA and all characters must be numerical digits. There is more we can test for but this will do for demonstration purposes.
So how can we write a test for this assuming our telephone text field in named “phone”? We can use a test that looks like this.
var numberfilter = /D/;
var returnval = numberfilter.test(phone.value);
if( phone.value == '' || returnval == false || phone.value.length != 10){
alert("Please type in a valid phone number.");
phone.focus();
return false;
}
What the code does here, is, it creates a test for digits and runs the test against the value entered in the phone field keeping the result.This test is based on a regular expression which, formated in the way it is, the Capital "D" tells the code to look for numeric digits and no other form of characters.
Next it checks is the phone field is blank, or if the number of characters is not equal to 10. If any of these tests fail, JavaScript will pass a message to the user asking them to put in a valid phone number. It then puts the cursor in the phone field and returns false; basically it aborts sending the form. If these tests pass then it simple moves on to the next field's test.