How To Only Allow Alpha Numeric Chars With JavaScript

前端 未结 3 1393
花落未央
花落未央 2020-12-01 23:40

Been playing around with JavaScript, and what Im trying to do is only allow certain characters in the pass word field - a-z, A-Z and 0-9.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 00:36

    The below solution will accept only the alpha numeric value and some special key like backspace, delete etc.

    If you want to add some other key then add to the array .

    If you want to add some special symbol add to the same array or create a new array and compare it on the function like ex: yourNewVariableName.indexOf(e.keyCode)

    var specialKeys = [8, 9, 46, 36, 35, 37, 39];
            function IsAlphaNumeric(e) {
                var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
                var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
                return ret;
            }
    Alphanumeric value:
    

提交回复
热议问题