[resolved] Validate email with if-statements

I’m having some trouble getting my if-statement right. If the user leaves email empty, or if it validates to false, I want the user to know this. Here’s the first function that validates email with regex:

function val_email() {
var email = document.getElementById(“email”).value;
var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+.([a-zA-Z])+([a-zA-Z])+/;
var isValid = pattern.test(email);

if (email != null && isValid == false) {
	return false;
}else if (email != null && isValid == true) {
	return true;
}

}

Then this function checks whether email has been left out, if it doesn’t evaluate…

function form_validate() {
var email = document.getElementById(“email”).value;
var log_in_pw = document.getElementById(“password”).value;

var sign_in = document.getElementById(“validate_sign_in”);

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

}

The problem is: after the first if-statement, it stops evaluating the else-if. Why is this so and can you help me fix it? Thx,

sob, it’s because I didn’t write return false…tried to delete the thread but couldn’t find the delete button. anyways, feel free to delete it. sry

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

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.