stop form during submission if it validates incorrectly

Posted by muqman on Stack Overflow See other posts from Stack Overflow or by muqman
Published on 2012-12-02T04:55:24Z Indexed on 2012/12/02 5:03 UTC
Read the original article Hit count: 146

Filed under:
|
|

I am trying to use JavaScript to validate forms but if the form doesn't validate, I don't want the form to be sent to the "action" page.

The validator:

<script>
    function formSubmit()
    {
    document.getElementById("signup_form").submit();
    var x=document.forms["signup_form"]["tname"].value;
    if (x==null || x=="")
      {
      alert("First name must be filled out");
      return false;
      }
    }
</script>

The form itself:

<form action="some_file.php" method="post" id="signup_form" name="signup_form" onsubmit="return formSubmit()">

But all this does is if the tname field empty, it will return an alert but as soon as the user hits ok, the form then redirects to some_file.php. What have I missed here?

The submit button:

<a href="" onclick="return formSubmit(); return false" class="purplebutton">Signup</a>

So what have I missed? How do I avoid this in the future?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html