如何通过jquery validate plugin执行条件客户端validation

在这里我给我的HTML。 我有一个下拉列表,显示很少的产品信息,并通过复选框显示爱好。 我想如果用户选择产品iPod然后validation将不会激发业余爱好复选框其他明智的火。 如何通过jquery validate plugin添加jquery规则来执行这种条件validation。

DateValTest


-- Select Product-- IPhone MacBook Pro iPod
Hobbies
           

现在我正在通过这种方式进行客户端validation

  var declarationsError = $('#Hobbies-error'); $('form').submit(function () { if ($("#SelectedProductId option:selected").text() != 'iPod') { if ($(".hobbycls:checkbox:checked").length <= 0) { declarationsError.empty(); declarationsError.append("Select Any Hobbie's checkbox"); declarationsError.show(); return false; } else { declarationsError.empty(); declarationsError.hide(); } } declarationsError.hide(); return true; }); $('.hobbycls').change(function () { if ($(this).is(':checked')) { declarationsError.empty(); declarationsError.hide(); // hide error message } });  

上面的脚本工作正常,但我想使用jquery validate plugin添加规则来做同样的事情。

所以请指导我需要编写的jqueryvalidation代码来执行相同的操作。 告诉我如何通过添加jquery规则来进行这种条件validation。 谢谢

生成的HTML中有一些错误:

  1. 不同元素的相同ID(即:爱好)
  2. 链接到无元素的标签:ie:label for =“Products”

您可以使用jQueryvalidation器添加新规则,以完全重复您在两个jQuery函数中执行的操作:

  1. $(’form’)。submit(function(){
  2. $(’。hobbycls’)。change(function(){

你忘了给出Hobbies-error元素,所以我使用了div。

在下面的代码片段中:

 var validator; // a new rule is required to test if iPod is selected and checkboxes are... $.validator.addMethod('checkboxMaxIfiPodNotSelected', function (value, elem, param) { var selectedOptionVal = $(param.selEleiSiPod).val().trim(); var selectedOptionText = $(param.selEleiSiPod).text().trim(); if (selectedOptionText != 'iPod') { if (selectedOptionVal.length > 0) { if ($(':checkbox.' + elem.classList[0] + ":checked").length <= param.max) { $('#Hobbies-error').empty().append("Select Any Hobbie's checkbox").show(); return false; } } else { $('#Hobbies-error').empty().append("Select a Product").show(); return false; } } $('#Hobbies-error').empty().hide(); return true; }); $(function () { // build the dynamic rules.... var myRules = {}; var myMessages = {}; $(':checkbox.hobbycls').each(function (index, element) { myRules[element.name] = { checkboxMaxIfiPodNotSelected: { max: 0, selEleiSiPod: '#SelectedProductId option:selected' } }; myMessages[element.name] = { checkboxMaxIfiPodNotSelected: function(params, element) { // it's not usefull to return a true error message because I used a div // but this is up to you how to manage and place the errors return ''; } }; }); // use the rules and messages with validator... validator = $('form').validate({ rules: myRules, messages: myMessages, submitHandler: function (form) { // for demo alert('valid form submitted'); // for demo return false; // for demo } }); }); 
     

DateValTest


Hobbies