Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with validating forms with both Javascript and PHP

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?

like image 820
LonelyWebCrawler Avatar asked Feb 23 '26 21:02

LonelyWebCrawler


2 Answers

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.

like image 51
Jose Faeti Avatar answered Feb 25 '26 10:02

Jose Faeti


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.

like image 42
T.J. Crowder Avatar answered Feb 25 '26 10:02

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!