我有一个JavaScript登录验证功能块,但我的if
阻止部分正常工作,即未检查AND(&&)之后的条件导致未对密码进行验证,这是我的代码段
function validateLogin(){
var userid = document.getElementById('user_id');
var passid = document.getElementById('pass_id');
if((userid.value.length < 3) && (passid.value.length < 6)) {
document.getElementById('user_error').setAttribute("style","color:red")
document.getElementById('user_error').innerHTML="invalid username/password.";
return false;
}
return true;
}
&#13;
<form id="login_form" name="login" onsubmit=" return validateLogin()" >
<div>
<input class="user_login_form" id='user_id' type="text" required tabindex="1" name="user_id" autofocus autocomplete=off placeholder ="User Name">
</div>
<div>
<input class="user_login_form" id='pass_id' required type="password" tabindex="2" name="user_pass" placeholder ="Password">
<p id ="user_error"></p>
</div>
<input class="user_login_submit" type="submit" id='btnLogin' tabindex="3" name="login_btnSubmit" value="LOGIN" >
&#13;
答案 0 :(得分:2)
这是if
的优化。如果第一部分为假,则由于false && Anything
导致false
您需要使用OR
function validateLogin() {
var userid = document.getElementById('user_id');
var passid = document.getElementById('pass_id');
if ((userid.value.length < 3) || (passid.value.length < 6)) {
document.getElementById('user_error').setAttribute("style", "color:red")
document.getElementById('user_error').innerHTML = "invalid username/password.";
return false;
}
return true;
}
<form id="login_form" name="login" onsubmit=" return validateLogin()">
<div>
<input class="user_login_form" id='user_id' type="text" required tabindex="1" name="user_id" autofocus autocomplete=off placeholder="User Name">
</div>
<div>
<input class="user_login_form" id='pass_id' required type="password" tabindex="2" name="user_pass" placeholder="Password">
<p id="user_error"></p>
</div>
<input class="user_login_submit" type="submit" id='btnLogin' tabindex="3" name="login_btnSubmit" value="LOGIN">
答案 1 :(得分:0)
你想在这里使用OR。因此,如果用户ID长度小于3或者passid长度小于6,则抛出错误。
if((userid.value.length < 3) || (passid.value.length < 6))