![](/img/trans.png)
[英]How to auto submit a form when 10 characters is entered in the input text field
[英]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.