user2373912
user2373912

Reputation: 185

Form validation with javascript not submitting

I've been having trouble with validating an email input in a form.

Now I'm able to alert the user if they didn't input an email, or if the input is incorrect. However, if the input IS correct, it still alerts that the input is incorrect.

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

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

Upvotes: 0

Views: 86

Answers (3)

Timigen
Timigen

Reputation: 1025

The reason you are getting the invalid email alert is this line of code:

else if (document.getElementById("email").value !== "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$")

This says if the content of the input tag with the id attribute of "email" does not equal the following string "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}$" then alert Please enter a valid email address.

What you want is to test that the input matches that regular expression like so:

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

if (inputString === '') {
    alert("Please enter your email.")
    return false;
}
else if(!patt.test(inputString)) 
{//if the regex you specified matches its valid email(according to your regex) so negate and display error msg 
    alert("invalid e-mail");
    return false;
}
else
{
     return true;
}

Upvotes: 1

Sireesh Yarlagadda
Sireesh Yarlagadda

Reputation: 13716

Try this: It returns boolean value based on its validity

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

    if (document.getElementById("email").value=="") {
        alert("Please enter your email.")
        return false;
    } else if (!validEmail(document.getElementById("email").value)){
        alert("Please enter a valid email address.");
        return false;
    } else {
        return true;
    }
};


function validEmail(e) {
    var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    return String(e).search(filter) != -1;
}

Upvotes: 0

Jason Fingar
Jason Fingar

Reputation: 3368

You are using the regular expression incorrectly; you don't want to compare the email string to the regex string directly; you need to use javascript's match() method to test your value against a regular expression. For example:

var regex = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$";
var matches = document.getElementById("email").value.match(regex);
if(!matches.length){
    alert("bad email");
    return false;
}

Upvotes: 0

Related Questions