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;
}

Download the files

Comments

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.

Posted on 12-10 by psaso

i have seen most of the way u solve peoples problem, and i like it very much. please, i need u to help me this time around. i have a problem (1) I want to disable alphabet text in a textfield. i want only number. using just html tag, cos i'm not good at javascript. (2) how do i disable submit button when the text field is empty using simple php code or html?

Posted on 12-09 by RItesh

what if the user copy and paste alphanumeric value?

Leave a comment