jQueryvalidation仅在选择某些单选按钮时

我在表单上有这么简单的validation:

 $(function() { $("#postform").validate({ rules: { post_title: "required", post_url: "required", post_code: "required", post_content: "required", post_tags: "required" } }); });  

但是如果没有检查某些单选按钮我不想要post_url或post_code,因为当我选择它们时它们会被隐藏。 例如这里是无线电:

 
  • </li
  • 然后这是隐藏或显示它们的jquery代码:

      jQuery(document).ready(function($) { $("input[name='post_category']").change(function() { $("#discussion-label").toggle(this.value == "12"); }); $("input[name='post_category']").change(function() { $("#code-container").toggle(this.value == "13"); $("#code-label").toggle(this.value == "13"); }); $("input[name='post_category']").change(function() { $("#link-container").toggle(this.value == "14"); $("#link-label").toggle(this.value == "14"); }); $("input#r1:checked").change(); $("input#r3:checked").change(); $("input#r4:checked").change(); });  

    因此,我们的想法是,当用户选择第一个单选按钮时,只会validationpost_title,post_content和post_tags。 如果用户选择第二个单选按钮,它也将validationpost_url字段,如果他们选择第三个单选按钮,则它将validationpost_code字段但不再是post_url,反之亦然。

    有人可以帮忙吗? 谢谢

    您可以通过使用具有“depends”值的对象而不是validation对象的字符串“required”来进行条件validation,如下所示:

     $("#postform").validate({ rules: { post_title: "required", post_url: { required: { depends: function() { return $('input[name=post_category]:checked').val() == '14'; } } }, post_code: { required: { depends: function() { return $('input[name=post_category]:checked').val() == '13'; } } }, post_content: "required", post_tags: "required" } }); 

    validation框架自动使用该函数来检查是否应该进行validation。 如果函数返回true,它将validation,否则不会。 在这种情况下,每个function都是查找哪个无线电被检查,然后将该无线电的值与我们需要的值进行比较,以便进行validation。