【问题标题】:How to disallow specific characters when entered in a form input in plain JavaScript?在纯 JavaScript 的表单输入中输入时如何禁止特定字符?
【发布时间】:2016-09-04 20:35:24
【问题描述】:

我正在尝试创建一个用户名文本框,如果它是以下任何一种(!,@,#,$,%,^,&,*,(,),+,=,;,: ,`,~,|,',?,/,.,>,

我们的想法不是事后进行检查,而是在点击的那一刻进行。我有两个这样做的想法,结果都不好。第一个 JS 脚本似乎根本不起作用,第二个 JS 脚本冻结了整个选项卡。

我当前的 HTML 代码是:

<form name = "RegForm" class="login">
   <input type="text" name="username" id="username" placeholder="Enter your username">
</form>

我的第一个 JS 脚本是: https://jsfiddle.net/ck7f9t6x

userID_textfield.onkeydown = function(e) {   
    var prohibited = "!@#$%^&*()+=;:`~\|'?/.><, \"";
    var prohibitedchars = prohibited.split("");
    var prohibitedcharcodes = new Array();

    for (var i = 0; i < prohibitedchars.length + 1; i++) {
        prohibitedcharcodes.push(prohibitedchars[i].charCodeAt(i));
        for (var a = 0; a < prohibitedcharcodes.length + 1; a++) {
            if (prohibitedcharcodes[a] === e.which) {
                return false;
            }
            else {
                return true;
            }
        }
    }
}

我的第二个 JS 脚本是: https://jsfiddle.net/2tsehcpm/

var username_textfield = document.forms.RegForm.username;
username_textfield.onkeydown = function(e) {
    var prohibited = "!@#$%^&*()+=;:`~\|'?/.><, \"";
    var prohibitedchars = prohibited.split("");
    var text = this.value.toString();
    var chars = text.split("");
    for (var i = 0; i < chars.length + 1; i++) {
        for (var a = 0; a < prohibitedchars.length + 1; a++) {
            if (chars[i] == prohibitedchars[a]) {
                chars[i] = null;
            }
        }
    }
    this.value = chars.join();
}

我的代码有什么问题,我应该怎么做?

任何有启发性的答案将不胜感激!

【问题讨论】:

    标签: javascript html arrays validation input


    【解决方案1】:

    我已经更新了你最初的小提琴here

    为了简单起见,我选择的方法是获取尝试按下的键的字符串字符,然后检查它是否在 prohibited 数组中。

    你应该注意到我改为使用 onkeypress 而不是 onkeydown 事件,因为第一个事件包括像 shift这样的修饰符> 使用 fromCharCode() 时的键,而另一个则不使用(因为按下键会检查完整的组合键)。

    代码

    el.onkeypress = function(e) {   
        // invalid character list
        var prohibited = "!@#$%^&*()+=;:`~\|'?/.><, \"";
        // get the actual character string value
        var key = String.fromCharCode(e.which);
        // check if the key pressed is prohibited    
        if(prohibited.indexOf(key) >= 0){
            console.log('invalid key pressed');    
            return false;
        }
        return true;    
    };
    

    【讨论】:

    • 所以,这就是为什么当我按下 shift + any 键时,它只显示 shift 的 charCode。非常有用的信息马特;简洁明了!
    【解决方案2】:

    prohibitedChars是一串不需要的字符。所以你可以将输入值拆分,然后使用indexOf方法与providedChars进行验证

    // String of prohibited chars
    var prohibitedChars = "!@#$%^&*()+=;:`~\|'?/.><, \"";
    var _input = document.getElementById("username");
    //Validate on keyup
    _input.addEventListener('keyup',function(){
    var _getIpValue = _input.value;
    
    _validateField(_getIpValue);
    })
    //This function does the actual validation
    function _validateField(ipVal){
    // split the input 
    var arrayString = ipVal.split("");
    //iterate through each of them and check if it match with any chars of prohibitedChars
    arrayString.forEach(function(item){
     // if item match it will retun -1
     if(prohibitedChars.indexOf(item) !== -1){
      alert(item +" Not allowed");
      _input.value = ""
     }
    })
    }
    

    查看JsFiddle

    【讨论】:

    • 代码在@user2181397 上运行良好,但正如我所说的,我更喜欢在不输入的情况下丢弃无效字符! 但是,我将保留部分.forEach() 的代码,因为这是检查我不知道如何使用的数组的一种方法!
    猜你喜欢
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多