jQuery limit fields to alphanumeric characters only

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 thoughts on “jQuery limit fields to alphanumeric characters only”

  1. 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

  2. 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.

Leave a Reply

Your email address will not be published.