이 올바른 방향을 가리켜 야 :
document.getElementById("user").onkeyup = function(){
var nonoUser = ["username", "admin", "administrator", "demo"];
nonoUser.indexOf(this.value) === -1 ? false : this.value = '';
}
데모 : http://jsfiddle.net/Le2xC/
나는 또한 당신이 그렇지 않으면 사용자가 여전히 사용할 수 있습니다뿐만 아니라,이 서버 측의 유효성을 검사하고 희망 당신의 "nono"사용자 이름.
// 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로 처리 하시겠습니까? 그것은 클라이언트 측 언어입니다, 아무도 소스를 볼 수 있습니다 .. –
만약 입력이 첫 번째 입력과 같지 않으면 반환 할 곳에 다른 곳으로 갈 것입니다. 그래서 else 블록을 제거하십시오. –
@Mathijs Flietstra는 정확합니다. 최소한 이것을 서버 측에서 검증하고 자바 스크립트 유효성 검사를 좋은 것으로 추가해야합니다. 이것에 대한 자바 스크립트 유효성 검사에 의존하는 것은 재앙이 될 수 있습니다! –