简体   繁体   中英

How to not post a form if validation is false?

Basically, I have a form in a PHP document that is posting to itself to save into my database. Although, I would like to only post this form if it validates correctly.

I need to validate this with Javascript and determine whether or not it should be posted.

If my validation function returns false , then the form should not be submitted. If my validation function returns true , then the form should be submitted.

I do not want to validate this server side with PHP since all my code is client side within the Javascript and would be an absolute nightmare to transfer it all to the server side.

Is this possible? If so, how?

In the HTML form, you need to latch onto the "onsubmit" event . This tag attribute executes a hunk of javascript when the submit button is pressed. The form is only POSTed, however, when the javascript returns a TRUE value. In order to stop the POST request, simply return FALSE Examples can be found here .

1) Michelle is correct: most Javascript frameworks (including jQuery and Dojo) offer a rich set of powerful tools that simplify client-side validation.

2) In principle, it's actually quite easy: just add an "onsubmit()" handler to your form:

Somewhere (for example, in your HTML header), you have a Javascript function "validateForm()". If the function returns "false", the form will NOT be posted to the remote server.

I believe this is exactly what you want, correct?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM