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?
Try this:
*Changes made to your code: *
– There is no need for formSubmit to try to submit the form! Just perform the validation checks and return
trueif you want the submission to proceed orfalseotherwise.Also you do not need to check for the
x == nullcase. If the textbox is empty, its value will be “”.What might be needed though is a check that x does not just contain spaces. If you do not care about supporting older browsers you can use the new Javascript trim function. If you care about backwards compatibility, either try one of the many javascript libraries that offer
trimor the following:If I just wanted to avoid submitting spaces I would have left the
var x=bit as it was and added the replace in the check making itif(x.replace(/\s/g, '') == ""). However, I also want to trim the input so that if the user enters ” user1″ or “user1 ” the form will send “user1”.You can see the three different versions versions working here:
http://jsfiddle.net/9LPfb/2/
http://jsfiddle.net/9LPfb/3/
http://jsfiddle.net/9LPfb/6/