我正在使用 jQuery 官方网站上提供的 jQuery 验证插件来验证我的表单。一切都很顺利,直到我必须传递规则,不是基于字段 name
,而是基于 class
或 id
。我做不到。
这是我如何使用 name="comment"
将规则传递到字段的示例。
这是我的 jQuery 代码
$("#comForm").validate({
rules: {
comment: {
required: true,
minlength: 5,
maxlength: 500
}
}
});
这是我的表格
<form id="comForm" action="#" method="post" >
<textarea rows="4" name="comment" placeholder="What do you think?" class="input-xxlarge" id="defaultform"></textarea></br>
<textarea rows="4" name="othercomment" placeholder="What do you think?" class="input-xxlarge" id="defaultform"></textarea></br>
<input type="submit" value="Rate!" class="btn btn-primary">
</form>
假设我想将规则传递到具有默认表单 id
的每个字段或具有 input-xxlarge
class
的所有字段。这可能吗?
最佳答案
是的,这是可能的,但你真的不应该使用重复的 id
...它是无效的 HTML,并且会导致 JavaScript 问题。如果需要重复项,请使用 class
。
使用内置的rules()
方法添加规则并按class
分配它们。 See documentation.
然后使用 jQuery 的 .each()
方法将规则应用于使用相同类
的所有匹配元素。
HTML:
<form id="myform">
<textarea class="myclass" name="field1" ></textarea>
<textarea class="myclass" name="field2" ></textarea>
</form>
jQuery:
$('#myform').validate({
// your other rules and options
});
// the following method must come AFTER .validate()
$('.myclass').each(function() {
$(this).rules('add', {
required: true,
minlength: 5,
maxlength: 500,
messages: {
required: "Required input",
minlength: "Must be at least {0} characters",
maxlength: "Must be less than {0} characters"
}
});
});
<强> Working DEMO
另外,类似于这个问题:
jQuery Validate set rule using wildcard to find target fields
关于jquery - 使用 jQuery Validate 插件将规则传递给类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14493850/