這裏的意見可以幫助你明白爲什麼你希望你的代碼是不工作:
// Your original code:
function arrayValidation() {
nonoUser = ["username", "admin", "administrator", "demo"];
valueOfInput = document.getElementById("user").value; // "user" here is id of input
for (var i = 0; i < nonoUser.length; i++) {
if (valueOfInput == nonoUser[i]) {
alert("you cant use this username");
} else {
// Using return here is the problem.
// This else block will run if a valid username was entered.
// The return statement stops execution of the function, thus ending the loop.
// So if the loop passes the test the first time, this return
// statement will stop the loop and function from completing
// the checks against the other keywords.
return;
}
}
}
這是你修改後的代碼爲你所期望的工作:
function arrayValidation() {
nonoUser = ["username", "admin", "administrator", "demo"];
valueOfInput = document.getElementById("user").value; // "user" here is id of input
for (var i = 0; i < nonoUser.length; i++) {
if (valueOfInput == nonoUser[i]) {
alert("you cant use this username");
// We can end the function check return here.
// There's no point checking the others, as we've found an invalid one.
return false; // Return a meaningful result
}
// No need for an else statement either.
}
}
由於許多已經指出,客戶端驗證應該被視爲可選的額外服務器端驗證。
您確定要在JavaScript中執行此操作嗎?這是一種客戶端語言,任何人都可以查看源代碼。 –
如果您的輸入不等於第一個輸入,它將返回其他位置。所以刪除其他塊 –
@Mathijs Flietstra是正確的 - 你應該至少在服務器端驗證這一點,並添加JavaScript驗證作爲一個很好的。依靠javascript驗證這可能是災難性的! –