如何禁止在纯JavaScript形式输入的表单中输入特定字符

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

本文关键字:输入 表单 字符 JavaScript 何禁止 禁止      更新时间:2023-09-26

我正在尝试创建一个用户名文本框,如果用户的输入是(!,@,#,$,%,^,&,*,(,),+,=,;,:,`,~,|,',?,/,.,><,,,").

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

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

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

我已经在这里更新了您的初始fiddle

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

您应该注意,我改为使用onkeypress事件,而不是onkeydown,因为第一个事件在使用fromCharCode()时包含类似shift键的修饰符,而另一个事件则不包含(因为按键检查完整的组合键)。

代码

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