0

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;
}
}
3
  • Have you looked at the jQuery validation plugin? It's very widely used and will likely save you a load of pain. Commented Nov 17, 2013 at 23:39
  • inline javascript is awful. Please don't do that. You really ought to let javascript handle the whole process using ajax. Commented Nov 17, 2013 at 23:41
  • Thank you both for your comments! I have not tried either of those options, but I thought for my small projects I would not need much. However, I do think I'll look those both up to try for this project, and to help me in later ones. Thanks! Commented Nov 17, 2013 at 23:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.