简体   繁体   中英

javascript onsubmit function not working for two input fields

I am trying to validate a form without using html5 validation as an exercise for a class, but I can't figure it out for the life of me.

I want to have an alert message pop up if the email and/or name is not valid/empty.

I have gotten to the point where the alert will pop up form the email OR the name field, depending which is first in the onsubmit function.

Any ideas would be greatly appreciated!

document.getElementById("frmContact").onsubmit = function() {

    var inputEmail= document.getElementById("email").value,
        emailPattern = new RegExp("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$");
    if (inputEmail==="") {
        alert("Please enter your email.")
        return false;
    } else if (!emailPattern.test(inputEmail)){
        alert("Please enter a valid email address.");
        return false;
    } else {
        return true;
    };

    var inputName= document.getElementById("name").value,
        namePattern = new RegExp("^[A-Za-z]+$");
    if (inputName==="") {
        alert("Please enter your name.")
        return false;
     } else if (!namePattern.test(inputName)){
        alert("Please enter a valid name.");
        return false;
    } else {
    return true;
    };
};

You return after the first one is validated, so the second field is never checked. Instead, have a local variable that is set to true by default, and set to false of either of the fields fail validation, and return it at the end.

    var valid = true;
    // ...
    if(inputEmail==="") {
        alert("Please enter your email.");
        valid = false;
    // ...

    return valid;
};

Maybe this doesn't work but the concept could be something like this...

document.getElementById("frmContact").onsubmit = function() {

    var inputEmail= document.getElementById("email").value,
        emailPattern = new RegExp("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$"),
        error = [],
        i = 0;

    if (inputEmail==="") {
        error.push("Please enter your email");
    } else if (!emailPattern.test(inputEmail)){
        error.push("Please enter a valid email address.");
    } 

    var inputName= document.getElementById("name").value,
        namePattern = new RegExp("^[A-Za-z]+$");
    if (inputName==="") {
        error.push("Please enter your name.")
     } else if (!namePattern.test(inputName)){
        error.push("Please enter a valid name.");
    } 

    if(typeof error !== 'undefined' && error.length > 0){
        alert("you submit the form correctly");
    } else {
        for(i = 0; i < error.length; i + 1){
            alert(error[i]);
        }
    }
};

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