tags:

views:

187

answers:

5

I have the typical HTML "contact me" page, i.e. name, e-mail address and message. Since I want to do input validation on the page itself using Javascript, I can't use a "submit" button, otherwise the attached Javascript function would be ignored. At least that's how I understand it, CMIIW.
I tried to load the next page wrting "location = mail.php" but it appears that the form parameters don't get passed to my php page this way.
How do I validate input in Javascript and pass parameters to my php page when ok?
TIA
Steven

+5  A: 

Use the onSubmit event. Attach it to your form and if it returns true then your form will be sent to the PHP page. Read more here.

scompt.com
Accepted for being first and to the point, even though scompt was too lazy to spell the solution out. But I can understand that; it's a hot day. :-)
stevenvh
+1  A: 

You should still use the submit button to submit the form, that is the correct behavior.

Input validation should be done using the <FORM>'s onSubmit event. It should look something like this:

<script>
    function validate() {
        var isFormValid = whatever; // validate form
        return isFormValid;
    }
</script>

<form action="your.php" method="POST" onSubmit="return validate()">
    <!---fields--->
</form>
Yuval A
You need to capture the return value of the validate method in your onsubmit handler.
David Dorward
right, fixed now.
Yuval A
+7  A: 

You can use a form with an onsubmit handler on it, that returns false if the validation failed. If the check is ok, return true and the form will submit normally.

You'd have a javascript function something like this:

function check_it_all() { 
  if (all_ok) {
     return true;
  } else {
     return false;
  }
}

And the form

<form action=.....  onsubmit="return check_it_all();">
....
</form>
ylebre
A: 

If possible can't you use a JavaScript library like Jquery? It probably would make your life alot easier and they have tons of plug-ins for validation.

Such as

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

chobo2
+1  A: 

the function validate() return a bool.
This will stop the submission if validate() returns false.

<input type="submit" onclick="return validate()" value="click" />

I am an aspx.net developer so I am used to putting the validation call on the button.

x13