开发者

Problem with validating forms with both Javascript and PHP

开发者 https://www.devze.com 2023-03-20 06:14 出处:网络
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

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 pro开发者_C百科blem 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.


Just don't submit the form unless valid.

 function validate() {

     var isValid = true;
     //Do all the validation
     if(isValid)
     {
        document.form_name.submit(); 
     }
    }


use onsubmit="return validate()" to validate html form or submit a form using submit(); a javascript method

0

精彩评论

暂无评论...
验证码 换一张
取 消