需要jQuery验证addMethod的帮助

时间:2010-07-12 15:43:24

标签: jquery validation

好的,所以我写这个函数是一个应用于复选框的更改事件。现在很明显我需要将它用作自定义验证器方法,因此当您点击“下一步”以逐步执行表单时它会运行。我有所有工作,我只是无法正确的规则的语法。

这是一个改变事件:

$('#MKDPT').change(function() {
if ($('#MKDPT').is(':checked')) { 
    var checked = false;
    var ckd = ['AMX1N','BMFNP','BMFNB','CFE1N','CBEXR','CBT1','CBTQL','CME1','CMEQL','CMX1','DCMX1','DMERT','DMEDL','ERX1N','ERXXN','EXC1N','EXD1N','EXR1N','EXI1N','IPE1','KCB1','LME1','DLME1','MPL1','NDQ1N','NDQL2','CEC1','ICEFI','NYM1','DNYM1','NYMQL','NYS1N','NYSLM','PNK1P','PNK2N','SMX1','CNC1N','CNS1N','MTL1N','MTL2N','WEA1'];
    $('#' + ckd.join(',#')).each(function() { // Select all these IDs
        if (this.checked) { // Is this one checked?
            checked = true;
        }
        return !checked; // Exit if any are checked 
    });
    if (!checked) { // None are checked
        MKDPTAlert1(); 
    }
}      
});

我尝试使用自定义验证规则:

$.validator.addMethod(
    "MKDPTOnly",
    function(value, element, params) {
    var checked = false;
    var ckd = ['AMX1N','BMFNP','BMFNB','CFE1N','CBEXR','CBT1','CBTQL','CME1','CMEQL','CMX1','DCMX1','DMERT','DMEDL','ERX1N','ERXXN','EXC1N','EXD1N','EXR1N','EXI1N','IPE1','KCB1','LME1','DLME1','MPL1','NDQ1N','NDQL2','CEC1','ICEFI','NYM1','DNYM1','NYMQL','NYS1N','NYSLM','PNK1P','PNK2N','SMX1','CNC1N','CNS1N','MTL1N','MTL2N','WEA1'];$('#' + ckd.join(',#')).each(function() { // Select all these IDs
        if (this.checked) { // Is this one checked?
            checked = true;
        }
        return !checked; // Exit if any are checked 
    });
    if (!checked) { // None are checked

    }
}, Alert("foo");
);

正如你所看到的那样,它已经破碎了。我希望这显示为警报,而不是标准错误放置。我需要使用var“ckd”作为参数吗?我并不完全清楚这些是如何工作的,但之前已经使用了很多帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

这是一种应该采用这种方法的替代方法:

$('#myForm').validate({
  rules:{
     MKDPT: {
       required: {
         depends: function(element){
           return $('.others:checked').length;
         }
       }
     }
  },
  messages:{
    MKDPT: 'foo'
  }
});

请注意,这假设您已经分配了其他复选框的集合others