Ang*_*tis 5 html javascript arrays validation input
我正在尝试创建一个用户名文本框,阻止用户的输入,如果它是这些(!,@,#,$,%,^,&,*,(,),+,=,;,:,`, 〜,|,',?,/,.,>,<,,,,").
这个想法不是在事后进行检查,而是在点击的那一刻.我有两个想法,这两个结果都很糟糕.第一个JS脚本似乎根本不工作,第二个JS脚本冻结了整个选项卡.
我目前的HTML代码是:
<form name = "RegForm" class="login">
<input type="text" name="username" id="username" placeholder="Enter your username">
</form>
Run Code Online (Sandbox Code Playgroud)
我的第一个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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的第二个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();
}
Run Code Online (Sandbox Code Playgroud)
我的代码出了什么问题,我应该做些什么呢?
任何有启发性的答案将不胜感激!
我已经在这里更新了您的初始小提琴。
为简单起见,我选择的方法是获取尝试按下的键的字符串字符,然后检查它是否在数组中prohibited。
您应该注意,我更改为使用onkeypress代替onkeydown事件,因为第一个事件在使用时包含诸如ShiftfromCharCode()键之类的修饰符,而另一个则没有(因为 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;
};
Run Code Online (Sandbox Code Playgroud)