开发者

Need Help with jQuery validate addMethod

Ok, so I wrote this function to be a change event applied to a checkbox. Now it is apparent I need to use it as a custom validator method, so it runs when you hit "Next" to step through the form. I have all that working, I just can't get the syntax of the rule right.

Here it is as a change event:

$('#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(); 
    }
}      
});

And my attempt at a custom validation rule:

$.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");
);

As you can see, it is broken. I would like this to display as an alert, not the standard error placement. Do I need to use the var "ckd" as a param? Im not really entirely clear on how those work but have used them before with a lot of help.

Thanks!


Here's an alternative method that ought to do the trick:

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

Note that this assumes you've assigned your collection of other checkboxes the class others.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜