jQuery使用通配符验证设置规则以查找目标字段 [英] jQuery Validate set rule using wildcard to find target fields
问题描述
是否可以通过通配符添加规则?我认为不可能设置像这样的规则...
Is there possibility to add rules by wildcard? I think it's not possible to set rules like this...
$("#form").validate({
// errorLabelContainer: $("div#error"),
errorElement: "p",
errorClass: "form-error",
rules: {
$("input[name*='x.child']"): {
required: true,
minlength: 5
}
}
});
推荐答案
使用内置的rules()
方法添加规则. 请参阅文档.
Use the built-in rules()
method to add rules. See documentation.
注意:您必须必须在调用.validate()
之后调用此方法.
Note: You must call this method after you call .validate()
.
$("#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
});
});
在向表单中动态添加字段时,此方法也非常有用.
This method can also be very useful when you are dynamically adding fields to your form.
以下与自定义messages:
结合使用.请注意,格式与在.validate()
...
The following to combine with custom messages:
. Note that the format is slightly different than when adding rules as options within .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
并像这样使用...
As mentioned elsewhere, you can also create a class
and use like this...
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")
}
});
});
这篇关于jQuery使用通配符验证设置规则以查找目标字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!