views:

72

answers:

1

Adding a validator to my form:

jQuery.validator.addMethod('whatever', function(val, el) {
// whatever goes here
}, 'A maximum of ' + $('#my_id_here').val() + ' categories can be selected.');

This doesn't fly. I always get undefined. Is this a good, simple way to do this?

Thanks

+1  A: 

Something like this:

$(document).ready(function() 
{    

    jQuery.validator.addMethod("validateCountries", function(value, element) {

                    alert('s'); 

                return this.optional(element) || /^\d{3}-\d{3}-\d{4}$/.test(value);
            }); 

    // add the validation rule   
    $("#form1").validate();    

    $("#lbCountries").rules("add", { validateCountries:true });   

});

Inside the Add method you can perform your validation!

UPDATE 1:

With dynamic text you will loose the error messages displayed. Here is a way to tackle that issue:

// add the validation rule   
    $("#form1").validate(    

    {   
       messages: { lbCountries: "please specify the countries" } 
    }

    ); 

The lbCountries is a ListBox control.

UPDATE 2:

You can attach another rule attribute with the rule as shown below:

  $("#lbCountries").rules("add", { validateCountries:true, noOfSelectedItems:3 }); 

Now, you can check for the rule when the event is fired:

$("#lbCountries").rules().noOfSelectedItems; // this will return 3 
azamsharp
But what if I had a list of checkboxes and I wanted to make sure that only 4 were checked, but that value can't be hardcoded? I need a way to make it sometimes say "Only <x> checkboxes can be selected.".
James
You can do a hack (not nice) by having a custom property on the checkbox like only = 4. Now, when you access the checkbox list you can find out how many checkboxes needs to be set and you can validate that!
azamsharp
The validation itself isn't the problem, I can just use a hidden for that. The specific part I'm having trouble with is making the *message* itself tailored to the number I'm looking for.
James
A better approach will be to extend the jQuery validation and add a new selector for noOfItemsSelected. Then you can make sure when you add a custom rule the noOfItemsSelected is always met!
azamsharp
See my updated answer!
azamsharp