javascript AJAX 调用后手动 jQuery 验证调用不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3840673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:25:38  来源:igfitidea点击:

Manual jQuery validation call after AJAX call not working?

javascriptjqueryjquery-validate

提问by Pawel

I have a mixed client-side/server-side validation using jQuery validation plugin. The validation happens on both submit and for some fields on change. The form is being submitted via AJAX. There is another validation going on the application just before updating the DB. If the data changes are not stored to the database due to this validation failing I'm returning the result via JSON to the JS method handling the AJAX form submission. Ideally I would raise an error with custom message passed from the backend to JS by something like $.validator.showErrors(obj); as discussed hereUnfortunately the validator.showErrors(...) method is not defined in that context:

我有一个使用 jQuery 验证插件的混合客户端/服务器端验证。验证发生在提交和某些更改的字段上。表单是通过 AJAX 提交的。在更新数据库之前,应用程序还会进行另一项验证。如果由于此验证失败而未将数据更改存储到数据库中,我将通过 JSON 将结果返回到处理 AJAX 表单提交的 JS 方法。理想情况下,我会通过诸如 $.validator.showErrors(obj); 之类的东西从后端传递给 JS 的自定义消息引发错误。正如这里所讨论的 不幸的是,validator.showErrors(...) 方法没有在该上下文中定义:

$(document).ready(function() {
    $('.form').each(function() {
    $(this).submit(function(e) {
        e.preventDefault();
        if ($.submitForm()) {
    (...)
            $.post(url, $.param(context), function(data) {
                if (!data.success) {
                    $.validator.showErrors(...);
                    //$("#basicdetails").validate();
                }
            }, "json");
        }
        (...)

You can also see that I've tried form revalidation which should also trigger appropriate error (although more of an hack that the real solution).

您还可以看到,我已经尝试过表单重新验证,这也应该触发适当的错误(尽管更多是真正的解决方案的 hack)。

I would like to retain static client-side validation and after ajax submission to be able to raise any errors that might have occurred on the backend.

我想保留静态客户端验证,并在 ajax 提交后能够引发后端可能发生的任何错误。

Thank you for any help you can provide.

感谢您提供任何帮助。

Pawel

帕维尔

回答by Nick Craver

.validate()is for setting upvalidation, to triggerit you should use .valid()like this:

.validate()用于设置验证,要触发它,您应该.valid()像这样使用:

$("#basicdetails").valid();