only allow English characters and numbers for text input

强颜欢笑 提交于 2019-11-28 18:55:46

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

<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

You can do something like this: http://jsfiddle.net/DveuB/1/

Then it's only 0-9, a-z and A-Z

$(function(){
    $("#user").keypress(function(event){
        if ((event.charCode >= 48 && event.charCode <= 57) || // 0-9
            (event.charCode >= 65 && event.charCode <= 90) || // A-Z
            (event.charCode >= 97 && event.charCode <= 122))  // a-z
            alert("0-9, a-z or A-Z");
    });
});

Update: http://jsfiddle.net/DveuB/4/
To prevent what @mu is talking about:

$("#user").keyup(function(event){
    if (event.altKey == false && event.ctrlKey == false)
        if ((event.keyCode >= 48 && event.keyCode <= 57 && event.shiftKey== false) ||
            (event.keyCode >= 65 && event.keyCode <= 90) ||
            (event.keyCode >= 97 && event.keyCode <= 122))
            alert("0-9, a-z or A-Z");
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {

  $('.clsAlphaNoOnly').keypress(function (e) {  // Accept only alpha numerics, no special characters 
        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;
    }); 
})
</script>

<body>

<input class='clsAlphaNoOnly' type='text'>
</body>
</html>

Think you have to write some if statements or something like that, that takes the keycode and validates it against some numbers that represent other keycodes:

for example: if(keycode < 80) return false;

I'm using this function.

By modifying RegExp you can get rid of any characters you don't like personally.

$(function(){
    $("#user").bind('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;
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!