必须至少选中一个复选框,并显示一条错误消息

时间:2015-07-22 10:50:52

标签: jquery validation

问题是: 应该只有一条消息。像

 Invalid:
    Please select at least one!

但错误显示为:

Invalid:
Please select at least one!
Please select at least one!

这是代码: HTML:

<input id="contact" class="contact_class" type="checkbox" number="12121" name="contact[]">
<input id="contact" class="contact_class" type="checkbox" number="252525" name="contact[]">

自定义验证方法:

$.validator.addMethod("contactcheck", function(value, elem, param) {
 return $(".contact_class:checked").length >= 1;
},"You must select at least one!");

验证表格为:

$("#frmsend").validate({
        debug:false, onsubmit: true, onfocusout: false, onkeyup: false,
        rules: {
            'contact[]': {    contactcheck: true }
        },
        messages: {
            'contact[]': { contactcheck: "Please select at least one!"    }
        }
        ,showErrors: vError
        ,submitHandler: vSuccess
    });

错误功能:

function vError(eM, eL) {
    if(eL.length===0) return;
    var arr=[];
    for(var err=0;err<eL.length;err++) {
            arr.push({ message: eL[err].message });
    }
    $("#showerrors").notification({caption: "Invalid:", messages: arr});
}   

1 个答案:

答案 0 :(得分:0)

您可以使用jQuery.inArray检查重复的错误消息。下面是你修改过的功能。

function vError(eM, eL) {
 if(eL.length===0) return;
   var arr=[];
   var msgAlrdyAdded = [];
   for(var err=0;err<eL.length;err++) {
      if(jQuery.inArray( eL[err].message, msgAlrdyAdded )==-1){
         arr.push({ message: eL[err].message });
          msgAlrdyAdded.push(eL[err].message); 
      }

   }
    $("#showerrors").notification({caption: "Invalid:", messages: arr});
 }