使用内置rules()
方法添加规则。 请参阅文档。
注意:调用后必须调用该方法。.validate()
jsFiddle 演示
$("#form").validate({
errorElement: "p",
errorClass: "form-error"
});
// the following method must come AFTER .validate()
$("input[name*='x.child']").each(function() {
$(this).rules('add', {
required: true,
minlength: 5
});
});
当您向表单动态添加字段时,此方法也非常有用。
以下与 custom 结合使用messages:
。请注意,格式与将规则添加为选项时略有不同.validate()
...
$("input[name*='x.child']").each(function() {
$(this).rules('add', {
required: true,
minlength: 5,
messages: {
required: "Required input",
minlength: jQuery.format("At least {0} characters are necessary")
}
});
});
如其他地方所述,您还可以像这样创建class
和使用...
jsFiddle 演示
HTML:
<input type="text" class="myclass" name="whatever" />
jQuery:
$("#form").validate({
errorElement: "p",
errorClass: "form-error"
});
// the following method must come AFTER .validate()
$('#form').find('.myclass').each(function() {
$(this).rules('add', {
required: true,
minlength: 5,
messages: {
required: "Required input",
minlength: jQuery.format("At least {0} characters are necessary")
}
});
});