only allow English characters and numbers for text input

前端 未结 7 679
旧巷少年郎
旧巷少年郎 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 03:53

    All answers above are fine but don't prevent copy and paste non-English characters.

    ‌Bellow code work for both (key press and copy-paste):

    <input type="text" name="text" oninput="this.value=this.value.replace(/[^A-Za-z\s]/g,'');">
    
    0 讨论(0)
  • 2020-12-05 03:56

    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;

    0 讨论(0)
  • 2020-12-05 04:02

    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

    0 讨论(0)
  • 2020-12-05 04:12

    <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

    0 讨论(0)
  • 2020-12-05 04:12

    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;
        });
    });
    
    0 讨论(0)
  • 2020-12-05 04:15
    <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>
    
    0 讨论(0)
提交回复
热议问题