I have a form text field that I want to allow only numbers and letters in. (i.e., no #$!, etc...) Is there a way to throw up an error and prevent the keypress from actually outputting anything if the user tries to use any character other than numbers and letters? I've been trying to find a plugin, but haven't really found anything that does this...
相关问题
- How to fix IE ClearType + jQuery opacity problem i
- jQuery add and remove delay
- Include empty value fields in jQuery .serialize()
- Disable Browser onUnload on certain links?
- how to get selected text from iframe with javascri
EDIT:
There are some other good answers here that will prevent the input from taking place.
I've updated mine since you also wanted to show an error. The replace can take a function instead of a string. The function runs and returns a replacement value. I've added an
alert
to show the error.http://jsfiddle.net/ntywf/2/
Well the patrick's answer removes character if it is wrong, to actually prevent character from being inserted into the field use
This way the letter will not come to textarea
You could try this extension:
Useage:
I found that combining validation on keypress and keyup gives the best results. Key up is a must if you want to handle copy pasted text. It is also a catch all in case of cross browser issues which allow non numeric values into your textbox.
The above jquery extension (ForceAlphaNumericOnly) is good but still allows the following characters through
!@#$%^&*()
On my Mac, when you press the shift key (keycode
16
) and then 1, it enters!
but the keycode is49
, the keycode for1
.