Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing only Alphanumeric values [duplicate]

Tags:

jquery

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?

like image 594
KayKay Avatar asked Nov 05 '12 16:11

KayKay


People also ask

How do I only allow alphanumeric characters in Excel?

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.

What is only alphanumeric allowed?

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.

How do I allow only letters and numbers in regex?

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_-]*$".

How do you make sure a string is only alphanumeric?

In summary, to determine if a given string is alphanumeric, use String. isalnum() function.


1 Answers

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; }); 
like image 200
Kami Avatar answered Oct 01 '22 09:10

Kami