Okay, so I want to validate a form with Javascript before I validate it with PHP. If the Javascript function, let's call it validate(), detects an error, I want to prevent the PHP from being executed.
There is only one way that I know of which would enable me to do so: Using a link instead of a submit button, like this:
<a href="javascript:validate()">Login </a>
This could be the function validate():
function validate() {
//Do all the validation
document.form_name.submit(); }
However, there is one problem with this: My PHP scripts cannot know when exactly the form is submitted. Without Javascript, I would do this:
if ($_POST[button_name])
Now, though, there is no submit button, so the expression becomes obsolete.
So, in summary my question is:
How can I validate a form with Javascript and prevent the PHP validation from being executed if there is an error?
You should have a submit button, so that even the users without js enabled can still send the form, and it will be validated by php.
With js you can prevent the form submission, then check for validation and submit after you have validate it correctly.
There is only one way that I know of which would enable me to do so: Using a link instead of a submit button
There's a submit event on forms for exactly this purpose. You hook the event, and if the form is not valid, cancel the submission. Then you can use a submit button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With