Form Validation - Phone Numbers

This is the form of validation I like the most: Prevent the user from inputting the wrong information. In this case I have a field for a phone number, and I only want the user to be able to input numbers (0-9) and country code prefix (+).

One might argue that I should instead remove unwanted characters on the server side instead, but I rather prevent that from happening at all. It's bloody annoying with users that write stuff like "none" or "-" instead of leaving the box empty when they don't have/want to give out their phone number on a web form.

Updated to support keys like backspace and del

The Source

JavaScript:
  1. function isValidPhoneNumbers(evt) {
  2.   if (evt.which != 0) {
  3.     var charCode = (evt.which) ? evt.which : event.keyCode
  4.     if (charCode == 43 || charCode == 8 || (charCode <57 && charCode> 47)) {
  5.       return true;
  6.     } else {
  7.       return false;
  8.     }
  9.   }
  10. }

HTML:
  1. <input onkeypress="return isValidPhoneNumbers(event)" type="text" />

Compability

  • IE 6+
  • Firefox
  • Opera
One Response to “Form Validation - Phone Numbers”
  1. mullet Says:

    d00d, your code doesn’t allow the user to type ‘9′

Leave a Reply

You must be logged in to post a comment.