user3002809
user3002809

Reputation: 3

JS Form Validation - Submit Button does nothing

I'm trying to validate my form, and the first alert works. But then when the user fills in correct data and clicks submit, the form does not submit anymore. Any help is appreciated, thanks!

<form name="register" action="register.php" onsubmit="return validateForm()" method="post">

// form stuff

function validateForm() {
if (!checkName() || !checkEmail()) {
    return false;
} else {
    return true;
}
}

function checkName() {
var name=document.forms["register"]["name"].value;
if (name==null || name=="") {
    alert("Please fill out your name");
    return false;
}
}

function checkEmail() {
var email=document.forms["register"]["email"].value;
var atpos=email.indexOf("@");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
    alert("Not a valid e-mail address");
    return false;
}
}

Upvotes: 0

Views: 165

Answers (1)

jameslafferty
jameslafferty

Reputation: 2182

You need checkEmail and checkName to return true when the email or name is present. What you've got now returns undefined.

Here is a fiddle showing the solution and here are the two functions rewritten:

function checkName() {
    var name = document.forms["register"]["name"].value;
    if (name == null || name == "") {
        alert("Please fill out your name");
        return false;
    }
    return true;
}

function checkEmail() {
    var email = document.forms["register"]["email"].value;
    var atpos = email.indexOf("@");
    var dotpos = email.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
        alert("Not a valid e-mail address");
        return false;
    }
    return true;
}

I do ultimately think you'll be happier if you wind up going to jQuery Validation, though.

Upvotes: 1

Related Questions