jQuery 验证插件 - 自动验证页面上的多个表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19208987/
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
Validation plugin - Auto validate multiple forms on a page
提问by TheNiceGuy
Currently I need to validate every form like this:
目前我需要像这样验证每个表单:
$(document).ready(function () {
$('#admin_settings_general').validate({
rules: {
admin_settings_application_title: {
required: true
}
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
}
});
});
I want that it automaticly validate the forms for every element with the required
tag.
我希望它自动验证带有required
标签的每个元素的表单。
How can I do that?
我怎样才能做到这一点?
回答by Sparky
Quote OP:
引用 OP:
"I want that it automaticly validate the forms for every element with the required tag."
“我希望它自动验证带有所需标签的每个元素的表单。”
Quote OP comment:
引用 OP 评论:
"i have to call
$('#admin_settings_general').validate()
for each of the forms currently. How can i call it without limiting it to one form?"
“我目前必须调用
$('#admin_settings_general').validate()
每种形式。如何调用而不将其限制为一种形式?”
To properly initialize .validate()
on allforms on a page, use a common selector such as the form
tag itself (or a class
). Since you cannot attach .validate()
to anyjQuery selector that represents multiple form
elements, use a jQuery .each()
. This is simply how this plugins methods were designed.
要在页面.validate()
上的所有表单上正确初始化,请使用公共选择器,例如form
标签本身(或 a class
)。由于您无法附加.validate()
到任何代表多个form
元素的jQuery 选择器,因此请使用 jQuery .each()
。这就是这个插件方法的设计方式。
$(document).ready(function() {
$('form').each(function() { // attach to all form elements on page
$(this).validate({ // initialize plugin on each form
// global options for plugin
});
});
});
Working DEMO: http://jsfiddle.net/6Fs9y/
工作演示:http: //jsfiddle.net/6Fs9y/