我想检查我的 <ul>
是否提交表格时是否有 child 。
下面是我的 html:
<form>
/*other input elements*/
<div class="attributes-added">
<ul name = "attributesAddedList">
// by default no element is present
</ul>
<input type = "submit" value = "save"> </div>
</form>
如您所见,默认情况下提供的 ul 有子级 ( <li>
)。用户需要动态添加它们,这不是问题。
但我需要的是,当我提交表单时,它应该检查 ul
是否有没有 child 在 jQuery validator
使用自定义函数。
我已经尝试过如下所示的验证器,但尚未取得丰硕成果。
$("#templateForm").validate({
rules: {
attributesAddedList:{
addedCategory: $(".attributes-added ul").has("li").length
}
},
message: {
attributesAddedList:{
addedCategory: "the message"
}
}
});
现在自定义函数
$.validator.addMethod("addedCategory", function(value, element, len) {
if(len < 0){
return false;
}
}, "choose a category");
有什么帮助吗?
最佳答案
我使用隐藏输入来添加规则, 但我建议使用提交处理程序,但这样您可以使用 .valid() 方法,而不必等待表单提交, 希望这有帮助
jQuery.validator.addMethod("hasAttributes", function(value, element) {
console.log('bla');
return $("ul > li").length > 0
})
console.log($("#templateForm").validate({
ignore: "",
rules: {
attr: {hasAttributes: true}
},
submitHandler: function (form) { // for demo
alert(this.valid()); // for demo
return false; // for demo
},
invalidHandler: function(event, validator) { alert('oops, no attributes'); }
}));
$("#templateForm").valid()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
<form id="templateForm">
/*other input elements*/
<div class="attributes-added">
<input type="hidden" id="attr" name="attr">
<ul name = "attributesAddedList">
// by default no element is present
</ul>
<input type = "submit" value = "save"> </div>
</form>
关于javascript - 在验证器中添加自定义规则以检查 <ul> 是否有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37236373/