2

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 writing 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 Answers 5

7

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>
Sign up to request clarification or add additional context in comments.

Comments

5

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.

1 Comment

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. :-)
1

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>

1 Comment

You need to capture the return value of the validate method in your onsubmit handler.
1

The function validate() returns 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.

Comments

-2

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/

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.