更新时间:2022-06-23 02:28:15
使用此插件无法动态打开/关闭表单的任何/所有部分的验证.
You cannot dynamically turn validation on/off for any/all parts of a form with this plugin.
但是,您可以使用 .rules()
方法动态添加,删除或覆盖您的随时遵守规则,为您提供类似的行为.
However, you can use the .rules()
method to dynamically add, remove, or over-ride your rules at any time, giving you a similar behavior.
然后,您可以使用 .valid()
方法来测试表单.
Then you can use the .valid()
method to test the form.
将它们分别放入专用的click
事件处理程序中.
Put them each inside dedicated click
event handlers.
$(document).ready(function() {
// initialize the plugin
$("#form1").validate({
ignore : '*:not([name]),:hidden'
// no rules; rules are set dynamically below
});
// Save Button
$('#save_button').on('click', function() {
// dynamically set the rules
$('input[name="email"]').rules('add', {
required: true,
....
});
// remove all rules from the other fields
$('input[name="city"]').rules('remove');
// force a test of the form
$("#form1").valid();
});
// Submit Button
$('#submit_button').on('click', function() {
// dynamically set the rules
$('input[name="city"]').rules('add', {
required: true,
....
});
// remove all rules from the other fields
$('input[name="email"]').rules('remove');
// force a test of the form
$("#form1").valid();
});
});
概念验证演示: http://jsfiddle.net/x6YWM/
Proof-of-concept DEMO: http://jsfiddle.net/x6YWM/
如果您有许多字段,可以通过在它们上设置适当的类(例如.ruleset1
和.ruleset2
)来简化此过程.然后,您可以使用.rules()
方法将它们定位为一个组.只需记住,如果选择器针对多个元素,则需要将它们包含在jQuery .each()
中.
If you have many fields, you can make this easier by setting appropriate classes on them like .ruleset1
and .ruleset2
. Then you can target them as a group with the .rules()
method. Just remember that you'll need to enclose them inside a jQuery .each()
if the selector targets more than one element...
$('.ruleset1').each(function() { // target multiple elements
$(this).rules('add', { // apply the rules to each
required: true,
....
});
});