Most client-side validation nowadays is usually made through onsubmit validations. Although it is pretty convenient, it may be quite annoying for a user to find only at the end that most of their inputs are invalid and must enter them once again. If onblur validations is not enough, keyperss validation is the next step.
Here is another alternative to the usual onsubmit validations for forms. Instead of validating a form only at the end, why not validate it as the user is typing their input. This is where keypress validations come in. We can capture it through the onkeypress event.
Here are some examples of keypress validations:
Only integers are allowed:
Only alphanumeric characters are allowed:
No spaces are allowed:
Here is an example keypress validation function:
function alphaOnly(evt)
{
var charCode = (evt.which) ? evt.which : window.event.keyCode;
if (charCode <= 13)
{
return true;
}
else
{
var keyChar = String.fromCharCode(charCode);
var re = /[a-zA-Z]/
return re.test(keyChar);
}
}
What this function does is
- capture the keypress character entered
- determine if the browser is navigator based or not by checking for the which or keyCode attribute
- most of the special character codes will be skipped
- validate the character entered with a regex pattern
To use a keypress validation for an input element, we must add its onkeypress attribute with the validation function we want:
<input type='text' onkeypress='return alphaOnly(event)' />
You can also download the Javascript source below:
Download javascript keypress validation script
PS: As I have always said before, client-side validation is no substitute for server-side validation. Client-size validation is more for usability and reducing some load from your server (through reduced rendering of error pages). So don’t be lazy!
UPDATE:
For those who are interested in the jQuery version, here is the sample code:
$("input").bind("keypress", function(evt)
{
var charCode = (evt.which) ? evt.which : window.event.keyCode;
if (charCode <= 13)
{
return true;
}
else
{
var keyChar = String.fromCharCode(charCode);
var re = /[a-zA-Z]/
return re.test(keyChar);
}
}









