I was trying to restrict a form’s field from only allowing the user to enter alphanumeric characters into it. I looked all around and couldn’t find a nice way to do it without a plugin, so I wrote my own bind function that you can attach straight to an element.

$("#yourFieldsElementId").bind("keypress", function (event) {
	if (event.charCode!=0) {
		var regex = new RegExp("^[a-zA-Z0-9]+$");
		var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
		if (!regex.test(key)) {
			event.preventDefault();
			return false;
		}
	}
});

If you would like to restrict the input to only be numeric then do this:

$("#yourFieldsElementId").bind("keypress", function (event) {
	if (event.charCode!=0) {
		var regex = new RegExp("^[0-9]+$");
		var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
		if (!regex.test(key)) {
			event.preventDefault();
			return false;
		}
	}
});

If you would like to restrict the input to only be alphabetical then do this:

$("#yourFieldsElementId").bind("keypress", function (event) {
	if (event.charCode!=0) {
		var regex = new RegExp("^[a-zA-Z]+$");
		var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
		if (!regex.test(key)) {
			event.preventDefault();
			return false;
		}
	}
});

If you’re wondering about the following line:

if (event.charCode!=0) {

It is there to double check that if the delete or backspace key is pressed.
If you don’t have this check then you cannot delete data.


4 Comments

raj · August 13, 2014 at 13:03

can you tell the regex for limiting input values to 10 or some particular values. and is it possible to reduce the code by the following (for only numbers)
$(‘#some_id’).keypress(function(event){
console.log(event.which);
if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
event.preventDefault();
}});
can you tell me the other examples using the above mentioned method

raj · August 13, 2014 at 11:22

how about restricting the input field limit like 10 digit number

aniruddh · May 5, 2013 at 14:33

wow. this is workied with out any R&D or anything. i jist put the code from here and it worked.

Thanks for sharing this piece of code.

    Andrew · May 5, 2013 at 17:01

    Glad it helped you out Aniruddh!

Leave a Reply

Your email address will not be published. Required fields are marked *