简体   繁体   中英

I am using the same logic that I used to validate the name to the email but for some reason it's not working

I am trying to create a validation for name and email but for some reason the email validation is not working. If remove my name validation it will work but it doesn't work together.As well as if I enter my name and leave the email empty it still does not send an alert.

 function validations(form) { var n = document.getElementById("nam").value; if (n == "") { alert("Please enter Name"); return false; } else { return true; } var em2 = document.getElementById("em1").value; if (em2 == "") { alert("Please enter EMAIL"); return false; } else { return true; } } 
 <form action="#" method="POST" onsubmit="return validations(this);"> <div class="name"> Name : <input type="text" id="nam" name="fullName"> </div> <div class="em"> Email : <input type="email" name="Email" id="em1"> </div> <button type="submit" class="btn btn-primary btn-lg">Save</button> </form> 

Your function always returns after checking the nam , whether its valid or not. You should early-return false if the nam isn't valid, but hold off with returning true until you've validated the entire form. Eg:

function validations(form) {
    // Check the name
    var n = document.getElementById("nam").value; 
    if (n == ""){
        alert("Please enter Name");
        return false ;
    }

    // Check the email
    var em2 = document.getElementById("em1").value; 
    if (em2 == ""){
        alert("Please enter EMAIL");
        return false ;
    } 

    // If we reached here, both the name and email are OK
    return true;
}

To make it more easy just use the HTML input type="email" with the attribut required . It will then verify that the user enter a valid email.

See the doc here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM