我想在以下 HTML 中使用 jQuery 验证插件:
<input data-validators="required" name="X2aasNr" type="text" value="Nedas" class="cleared" id="">
如您所见,我使用名为 data-validators
的自定义属性。对于这种情况,我如何使用 jQuery 验证插件?
最佳答案
引用OP:
<input data-validators="required" ...
"As you can see, I use a custom attribute named
data-validators
. How can I use the jQuery Validation plugin for this case?"
你不能。 The plugin was not written to recognize that attribute .
但是,您可以按照以下方法定义验证规则:
<小时/>1) 在 .validate()
$(document).ready(function() {
$('#myform').validate({
rules: {
fieldName: {
required: true
}
}
});
});
注意:如果您的字段名称
包含特殊字符,例如括号或点,you must enclose the name
in quotes ...
$(document).ready(function() {
$('#myform').validate({
rules: {
"field.Name[234]": {
required: true
}
}
});
});
<小时/>
2) 由类
声明:
<input name="fieldName" class="required" />
<小时/>
3) 通过 HTML5 验证属性声明:
<input name="fieldName" required="required" />
<小时/>
4) 使用 the .rules()
method 声明:
$('input[name="fieldName"]').rules('add', {
required: true
});
<小时/>
5) 通过使用 the .addClassRules()
method 将一个或多个规则分配给您自己的类
:
$.validator.addClassRules("myClass", {
required: true
});
然后应用到您的 HTML:
<input name="fieldName" class="myClass" />
<小时/>
6) 按字段类型声明:
<input name="fieldName" type="email" />
关于具有自定义属性的 jQuery 验证插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17789372/