Form Validation - Phone Numbers
May 15th, 2007 by SubZane
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:
-
function isValidPhoneNumbers(evt) {
-
if (evt.which != 0) {
-
var charCode = (evt.which) ? evt.which : event.keyCode
-
if (charCode == 43 || charCode == 8 || (charCode <57 && charCode> 47)) {
-
return true;
-
} else {
-
return false;
-
}
-
}
-
}
HTML:
-
<input onkeypress="return isValidPhoneNumbers(event)" type="text" />
Compability
- IE 6+
- Firefox
- Opera
d00d, your code doesn’t allow the user to type ‘9′