jQuery Validate Plugin: How can I add groups to a validator after its been initialized?

I recently faced the same problem and found a different solution.

The Scenario

We have a table which grows dynamically as users add (or delete) rows. Each new row contains several elements, and we want each rows's input elements to be in a single validation group--one per row--because we only want one error label for each row. Because the rows are added dynamically--well after we call $('#the-form').validate()--we needed a way to add a new group each time the user adds a row.

Our Solution

We hacked the validator object by directly modifying its groups member:

// on document ready:
validator = $('#the-form').validate({
    groups: ...,
    rules: ...,
    messages: ...,
    etc.
});

...

// later, when we need to add a new validation group:
validator.groups['first_name_row_5'] = 'full_name';
validator.groups['last_name_row_5'] = 'full_name';

Those last two lines are equivalent to

groups: {full_name: 'first_name_row5 last_name_row_5'}

in the validator options, but can be added after the initial call to validate().

It's a hack into the internals of jquery.validate, but it works (with jquery validate v1.9.0).


Finally, to directly answer the OP's question: instead of this:

$("#mc-embedded-subscribe-form").validate().groups = { username: "FNAME LNAME" };

try this:

var validator = $("#mc-embedded-subscribe-form").validate();
validator.groups['FNAME'] = 'username';
validator.groups['LNAME'] = 'username';

I was looking for a way to do this too and found a solution in the jQuery help forum: http://forum.jquery.com/topic/jquery-validate-defining-groups-dynamically

var getGroups = function() {
    var result = {};
    $('#myTable tr').each(function(i) {
        var field1Name = $(this).find('.field1').attr('name');
        if (field1Name != undefined) {
            var field2Name = $(this).find('.field2').attr('name');
            result['fieldPair_' + i] = field1Name + ' ' + field2Name;
        }
    });
    return result;
}

$('#myForm').validate({  groups: getGroups() });