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

标签 javascript jquery html jquery-validate

我想检查我的 <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/

相关文章:

javascript - 在您正在构建的网站中禁用 JavaScript

javascript - 如何在JointJs中动态设置字体大小?

javascript - Jquery 验证器和已隐藏的字段

javascript - 使用来自前端的 Oauth 密码流程进行身份验证

javascript - 我们可以只使用 css 为标签做输入吗?

jquery - Rails UJS 确认框取消按钮回调

html - 在 ionic 标签内插入换行符

python - 我如何使用 CD 和 LS 等 Linux 终端命令?

javascript - 数据表(https ://datatables.net/)分页参数与服务器端不匹配

javascript - 从列表数组中追加一个值 - React Native