Validating Common Form Input - Part 4

Published on 25th of September 2008. Copyright Tavs Dokkedahl. Displayed 1218 time(s)

Validating phone numbers

This one is far more simple than validating names as phone numbers only consist of digits.

To validate a phone number 8 digits long

 1 function validate(form) {
 2   // Regular expression for a phone number
 3   // \d is equivalent to [0-9]
 4   var rgx = /^\s*\d{8}\s*$/;
 5   if(!rgx.test(form.elements.phone.value))
 6     return false;
 7   return true;
 8 }

Very simply indeed. Not all countries have phone numbers of uniform length. To test for a number which has at least 7 digits

 1 function validate(form) {
 2   // Regular expression for a phone number
 3   // \d is equivalent to [0-9]
 4   var rgx = /^\s*\d{7,}\s*$/;
 5   if(!rgx.test(form.elements.phone.value))
 6     return false;
 7   return true;
 8 }

Phone numbers can be entered in many ways - some write 12345678 others write 12 34 56 78. Too allow for any number of spaces and weird scenarios

 1 function validate(form) {
 2   // Regular expression for a phone number
 3   // \d is equivalent to [0-9]
 4   var rgx = /^(\s*\d+\s*)+$/;
 5   if(!rgx.test(form.elements.phone.value))
 6     return false;
 7   return true;
 8 }

but again we loose the ability to count the number of digits. The only way to do this is first remove any spaces then do the validation

 1 function validate(form) {
 2   // Shortcut to save writing
 3   var elm = form.elements;
 4   // Remove spaces
 5   elm.phone.value = elm.phone.value.replace(/\s*/g,'');
 6   // Regular expression for a phone number
 7   // \d is equivalent to [0-9]
 8   var rgx = /^\d{5,11}$/;
 9   if(!rgx.test(elm.phone.value))
10     return false;
11   return true;
12 }

The above will validate any phone number consisting of between 5 and 11 digits no matter how many spaces the user choose to enter.

Some times we need to allow for international dialing codes. These always start with a plus. We apply the same tactic to first remove any spaces and then check for an optional +

 1 function validate(form) {
 2   // Shortcut to save writing
 3   var elm = form.elements;
 4   // Remove spaces
 5   elm.phone.value = elm.phone.value.replace(/\s*/g,'');
 6   // Regular expression for a phone number
 7   // \d is equivalent to [0-9]
 8   var rgx = /^\+?\d{11}$/;
 9   if(!rgx.test(elm.phone.value))
10     return false;
11   return true;
12 }

This will validate a number of exactly 11 digits with an optional leading +.

« Part 3 Part 5 » 

Leave a comment

Name

Email (if you want a response)

Comment (no HTML)

Spam challenge
Sorry to bother you but spam is a royal pain, so please answer this simple question to verify that you are in fact human(oid)

Question: "What is the name of the programming language which this website is about?"

Answer: