only allow English characters and numbers for text input

前端 未结 7 680
旧巷少年郎
旧巷少年郎 2020-12-05 03:42

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 re

相关标签:
7条回答
  • 2020-12-05 04:19

    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");
    });
    
    0 讨论(0)
提交回复
热议问题