views:

2576

answers:

3

How do I block special characters from being typed into an input field with jquery?

+1  A: 

Use a jQuery Validation plugin, and allow only alphanumerical characters.

Tomas Lycken
That means the form won't send. It won't restrict people from entering certain characters
nickf
It could easily be used to validate each change, simply by hooking the .validate() method to the .keyup() event (or similar).
Tomas Lycken
A: 

this is an example that prevent the user from typing the character "a"

$(function() {
$('input:text').keydown(function(e) {
if(e.keyCode==65)
    return false;

});
});

key codes refrence here:
http://www.expandinghead.net/keycode.html

Marwan Aouida
I would think that all of the keycodes that you do not want to allow can be overwhelming to try and manage.
RSolberg
I didn't understand, what is wrong?
Marwan Aouida
If you want to restrict someone to only be able to enter numbers 1 through 5, you end up managing 5 keycodes within your code.
RSolberg
+3  A: 

Take a look at the jQuery alphanumeric plugin. http://itgroup.com.ph/alphanumeric/

//All of these are from their demo page
//only numbers and alpha characters
$('.sample1').alphanumeric();
//only numeric
$('.sample4').numeric();
//only numeric and the .
$('.sample5').numeric({allow:"."});
//all alphanumeric except the . 1 and a
$('.sample6').alphanumeric({ichars:'.1a'});

You can take this a step further to by adding masked inputs...

RSolberg