[resolved] Validate email with if-statements

Not a problem. This is something that others can learn from too. I will mark the thread as being resolved.

I take it that you have solved your problem by adding a second return statement, like this?

function form_validate() {
    ...
    if (email == "") {
        sign_in.innerHTML = "email is missing";
        return false;
    } else if (val_email() == false) {
        sign_in.innerHTML = "incorrect e-mail format";
        return false;
    }
}

If so, there is an improvement that you can make that will render the code more resilient to further problems. There are other things that you can do to make things even more resilient, such as by being more specific and instead of return false, you can prevent the default action. This helps to prevent unwanted side-effects because return false also prevents the event from bubbling further up the DOM, which can be an annoying trap if it’s not known.

Here’s that improvement, where an isValid flag is used to determine if the validation was successful or not.

function form_validate(evt) {
    var isValid = true;
    ...
    if (email == "") {
        sign_in.innerHTML = "email is missing";
        isValid = false;
    } else if (val_email() == false) {
        sign_in.innerHTML = "incorrect e-mail format";
        isValid = false;
    }
    if (!isValid) {
        evt.preventDefault();
    }
}
2 Likes