How to Prevent Special Non Alphanumeric Chars in an Input with jQuery

jQuey logo scrivi meno e fai di più

So the trick we are going to see today it’s an input where we avoid the insertion of special chars, such as esclamation marks (!), percentage (%), allowing only lettes and numbers.
The script allow the use of the arrows, backspace and delete button, preventing anything else.

Bind the keypress event on our input

The first thing to do it’s binding the keydown event on our input text. So:

Accept only letters and numbers to be entered

Next step it’s read the pressed key, and next decide if that char it’s good for our purposes or not.
We use the e.which to read the numerical value of the input, and next we can add an if to accept only numbers and letters.
The group of keys with value between 65 and 90 are the letter of the alphabeth, between 48 and 57 are the numbers on the top of the keyboard, and from 96 and 105 are the keys in the numeric keypad.

To discriminate those letters we use a simple if.

Allow the use of arrow keys and delete and backspace

The chars we would allow the use, such as backspace and delete are numbered as 8,27,46 and between 35 and 40. In my this example I don’t accept the enter key either, but if you need it for your app the keycode it’s 13.

And this is the result:

Download the example

Lascia un commento!