Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

only allow English characters and numbers for text input

Live Demo: http://jsfiddle.net/thisizmonster/DveuB/

How can I change this so that the input only allows the characters A-Z, a-z, 0-9 while typing, without using a regular expression?

like image 223
Gereltod Avatar asked Aug 22 '11 07:08

Gereltod


People also ask

How do you restrict characters in input?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

How do I make input type text only accept numbers?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.


2 Answers

Assuming you also want to accept spaces:

$("#user").keypress(function(event){
    var ew = event.which;
    if(ew == 32)
        return true;
    if(48 <= ew && ew <= 57)
        return true;
    if(65 <= ew && ew <= 90)
        return true;
    if(97 <= ew && ew <= 122)
        return true;
    return false;
});

If you don't want to accept spaces then remove the if(ew == 32) return true;

JSFiddle

like image 187
Paul Avatar answered Sep 23 '22 16:09

Paul


<input type="text" id="firstName"  onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" />

The ASCII Character Set : https://www.w3schools.com/charsets/ref_html_ascii.asp

like image 28
Siya Matsakarn Avatar answered Sep 21 '22 16:09

Siya Matsakarn