繁体   English   中英

如何在纯JavaScript中输入表单输入时禁止使用特定字符?

[英]How to disallow specific characters when entered in a form input in plain JavaScript?

我正在尝试创建一个用户名文本框,阻止用户的输入,如果它是这些(!,@,#,$,%,^,&,*,(,),+,=,;,:,`, 〜,|,',?,/,。,>,<,,,,“)。

这个想法不是在事后进行检查,而是在点击的那一刻。 我有两个想法,这两个结果都很糟糕。 第一个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();
}

我的代码出了什么问题,我应该做些什么呢?

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

在这里更新了你的初级小提琴。

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

你应该注意到我改为使用onkeypress而不是onkeydown事件,因为第一个包含修饰符,如使用fromCharCode()时的shift键,而另一个不包括(因为keypressed检查完整的键组合)。

代码

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;    
};

prohibitedChars是一串不需要的字符。因此,您可以拆分输入值,然后使用indexOf方法验证prohibitedChars

// 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM