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

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)" />

This is the javascript function to use:

function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}

 

Plaats een reactie