Possible Duplicate:
How to prevent users from entering invalid characters inside an input field
I have 3 textboxes on a page. One of them should allows numbers, the other alphabets and the 3rd either numbers or alphabets.
Since this is the only requirement, I do not want to use the validation plugin, or any other 3rd party plugin. How can I do this by creating my own plugin using pure jQuery?
This is what I have done but I get a feeling that the code will become too long
$(this).keydown(function(e) { var key = e.charCode || e.keyCode || 0; return ( key == 8 || key == 9 || key == 46 || (key >= 37 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105)); });
http://jsfiddle.net/Cvus8/
Can anyone tell me which si the best way to approach this issue?
1. Select the column you want to limit the entry, and click Data > Data Validation > Data Validation. 3. Click OK, and then the selected column only allowed entry numeric characters.
For some computer purposes, such as file naming, alphanumeric characters are strictly limited to the 26 alphabetic characters and 10 numerals. However, for other applications -- such as programming -- other keyboard symbols are sometimes permitted.
You can use regular expressions to achieve this task. In order to verify that the string only contains letters, numbers, underscores and dashes, we can use the following regex: "^[A-Za-z0-9_-]*$".
In summary, to determine if a given string is alphanumeric, use String. isalnum() function.
The better solution might be to go with regular expression based checks. Example below will limit only alphanumeric characters in the field with id text
:
$('#text').keypress(function (e) { var regex = new RegExp("^[a-zA-Z0-9]+$"); var str = String.fromCharCode(!e.charCode ? e.which : e.charCode); if (regex.test(str)) { return true; } e.preventDefault(); return false; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With