简体   繁体   中英

Submitting form with jQuery & validation

I am using validate.js to validate a form. If the form does not validate, a message is displayed when the user tries to submit a form, showing the errors. If the user passes validation, then a success message pops up. The problem is, the form does not actually send/take action, because validate.js is preventing the default behavior.

The code that is preventing the form from sending is:

if (event && event.preventDefault) {
    event.preventDefault();
} else if (event) {
    event.returnValue = false;
}

You can see full js here: http://jsfiddle.net/DBfks/

It seems to me that the above code prevents default behavior of the form submission IF the form does not pass validation, but if it does, then the form should submit. Is this correct? Any ideas on how to make the form submit INSTEAD of showing a success message (please see jsfiddle to see how the success and error messages work)

Thanks in advance. You can see a working demo here .

Add

 $("#myForm").submit();

Where you want to submit the form.

In your jsFiddle you got this if/else:

if (errors.length > 0) {
                        SELECTOR_ERRORS.empty();

                        for (var i = 0, errorLength = errors.length; i < errorLength; i++) {
                            SELECTOR_ERRORS.append(errors[i].message + '<br />');
                        }

                        SELECTOR_SUCCESS.css({ display: 'none' });
                        SELECTOR_ERRORS.fadeIn(200);

                    } else {
                        SELECTOR_ERRORS.css({ display: 'none' });
                        SELECTOR_SUCCESS.fadeIn(200);

                    }

(Okay, copy-pasting kinda messed it up!)

So, if there were any errors, add al the errors to the error box and show it. else show you validated it. But that isn't what you want, you should submit the form there:

else {
    $("#yourform").submit();
}

The reason the code was not working with jQuery submit was because the preventDefault method prevented jQuery from submitting the form. The fix was to simply remove these lines:

if (event && event.preventDefault) {
    event.preventDefault();
} else if (event) {
    event.returnValue = false;
}

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