Search code examples
javascriptand-operator

Javascript AND (&&) operator is not working inside if block


I have a JavaScript login validation block, however my if block is partially working, i.e condition after the AND(&&) is not being checked resulting not applying validation on password, here is my code snippet.

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" >


Solution

  • It's optimization of if. If first part is false, then further comparisons are not executed because of false && Anything results in false

    You need to compare using 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">