Allow only numeric input or disallow spaces with Javascript

This is a very easy way to restrict users from inputting any characters other then numbers or restrict users from entering spaces in e.g. login and password fields. You can restrict other characters by adding the charcodes to the function. You can check the charcodes at cambiaresearch.com
You can download the files below.
Usage:
Load in the javascript file and add onkeypress=“return isNumberKey(event)” in the input tag to restrict users from entering anything other then numeric input. Add onkeypress=“return nospaces(event)” to restrict users from entering spaces.
like so:
< input type="text" name="numeric" id="numeric" value="" maxlength="12" onkeypress="return isNumberKey(event)" />
< input type="text" name="numeric" id="numeric" value="" maxlength="12" onkeypress="return nospaces(event)" />
the javascript file contains this:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Posted on 20-10 by Peter
Thanks for the tip! Note: you repeated the isNumberKey(evt) function in your article: the second one should be replaced by nospaces(evt). It's correct in the download files though.Posted on 20-10 by steven dobbelaere
thanks for noticing. I've overlooked this.