Rahul
Rahul

Reputation: 2071

JavaScript form validation second if statement not working

I'm starting simple JavaScript form validation. I write two statement, first if statement working well but second one is not. But this two if statement separately working. I don't understand what I'm wrong. Here is the HTML code:

<form id="loginForm" name="loginForm" method="post" action="my-profile.html">
    <div class="form-group">
        <label>Email</label>
        <input type="email" name="email" id="eMail" placeholder="[email protected]" class="form-control" required="required" />
        <span class="erRor" id="error1">Please input valid email address</span>
    </div>
    <div class="form-group">
        <label>Password</label>
        <input type="password" placeholder="Password" name="password" id="pasSword" class="form-control" required="required" />
        <span class="erRor" id="error2">Invalid email and password</span>
        <span class="erRor" id="error3">This field should not be empty</span>
    </div>
    <div class="form-group">
        <button type="submit" onclick="return validate();">Login</button>
    </div>
</form>

JavaScript code here:

function validate(){
    /* email validation */
    var changeColor = document.getElementById("eMail");
    var error1 = document.getElementById("error1");
    var email1 = document.loginForm.email;
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    if(!re.test(email1.value)){
        changeColor.style.border = "2px solid red";
        error1.style.display = "block";
        return false;
    }

    /* empty fild check for password field */

    var pas = document.getElementById("pasSword");
    var error3 = document.getElementById("error3");
    var password = document.loginForm.password;
    if(password.value === ""){
        pas.style.border = "2px solid red";
        error3.style.display = "block";
        return false;
    }
}

Please help me out of this.

Note: I want to learn "AS YOU TYPE JavaScript for validation". I haven't find any proper tutorial or desiccation.

Upvotes: 0

Views: 295

Answers (1)

Rajesh
Rajesh

Reputation: 24955

You are using return false, hence second validation is not working.

Try this:

var valid = true;
if(conditoin_one){
    valid = false;
    // update error element
}
if(conditoin_two){
    valid = false;
    // update error element
}
return valid;

Upvotes: 2

Related Questions