在验证器中添加自定义规则以检查<ul>具有元素

to add a custom rule in validator to check <ul> has element

本文关键字:lt ul 元素 gt 检查 验证 添加 自定义 规则      更新时间:2023-09-26

我想在提交表单时检查我的<ul>是否有子项。下面是我的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>)。用户需要动态添加它们,这不是问题。但我需要的是,当我提交表单时,它应该使用自定义函数检查uljQuery 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>