jQuery 如何在不使用提交按钮的情况下触发验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5785510/
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-08-26 19:49:00  来源:igfitidea点击:

How to trigger validation without using a submit button

jqueryajaxvalidationplugins

提问by Ken

I am using the jQuery Validation plugin and trying to trigger the validation/submit with an alternate button. I would like to create a jquery function that will change the css, and then run the validate function. I have looked at previously answered questions but have not found any that address this issue with regards to the Validation plugin and and the submitHandler function. Any suggestions?

我正在使用 jQuery 验证插件并尝试使用备用按钮触发验证/提交。我想创建一个将更改 css 的 jquery 函数,然后运行验证函数。我查看了以前回答的问题,但没有找到任何解决与验证插件和 submitHandler 函数相关的问题的问题。有什么建议?

UPDATE TO QUESTION: The button that I would like to use is placed outside of the form. What is the best way to submit and validate a form with a button located outside of that form?

问题更新:我想使用的按钮位于表单之外。使用位于表单外部的按钮提交和验证表单的最佳方法是什么?

Here is the code:

这是代码:

$("#edit-button").click(function(event) {

$('#postAccordion2').css('padding-bottom', '0px');
$('#edit-button').css('display','none');
$("#applicant-form").validate({
    submitHandler: function(form) {
            $(form).ajaxSubmit({                  
                type: "POST",
                data: {
                    "firstName" : $('#firstName').val(),
                    "lastName" : $('#lastName').val()
                    },
                dataType: 'json',
                url: './includes/ajaxtest.php',
                error: function() {alert("doh!");},
                success: function() {alert("yippee!");},

    }    

  });

return false;   
   },
        errorPlacement: function(error,element) {
                        return true;
                },
        rules: {
            "firstName": {
                required: true,
                minlength: 1
                },  
            "lastName": {
                required: true
                }
        }


});
   });

回答by Kyle Rogers

You should be able to just call valid on whatever element you like:

您应该能够在您喜欢的任何元素上调用 valid :

$('selector').valid();

Here are some references:

以下是一些参考:

http://docs.jquery.com/Plugins/Validation/valid

http://docs.jquery.com/Plugins/Validation/valid

http://docs.jquery.com/Plugins/Validation/validate

http://docs.jquery.com/Plugins/Validation/validate

回答by Peter Olson

You have to call validatewith no arguments to trigger the validate function, like this:

您必须validate不带参数调用才能触发验证函数,如下所示:

$("#applicant-form").validate();