简体   繁体   中英

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

On our site we are using an embedded sign-up form from our ESP that uses the jQuery validate plugin. We are customizing the form a bit, adding a couple of custom fields (first name, last name) and we want them to be grouped so there is only one error message for both the fields.

Since the form's validator has already been initialized I need to add in a few things dynamically. The plugin provides the rules( "add", rules ) method to add in validation rules dynamically, although we are just using class names to do this anyhow. But there is no clear way to set the groups option after the validator has been initialized.

I've tried a few different things to accomplish this, but none some to be working:

var settings = $("#mc-embedded-subscribe-form").validate().settings;
$("#mc-embedded-subscribe-form").validate($.extend(settings, {
    groups: {
        username: "FNAME LNAME"
    },
    errorPlacement: function(error, element) {
        if (element.attr("name") == "FNAME" || element.attr("name") == "LNAME") {
            error.insertAfter("#username_group");
        } else {
            error.insertAfter(element);
        }
    }
}));

The errorPlacement function is added to the validator, but not the groups.

I've also tried setting the groups option explicitly, but that has no effect either.

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

I'm completely stumped as how to accomplish this.

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

I tried every method I could find to dynamically add groups. The only one that worked for me was based on Ron's method above. I had a table that had rows that were dynamically added, each containing a number of fields.

// Names of fields within each table row that's dynamically added
var validateNames=["field1","field2","field3"];    

// This function overwrites all validator groups and is called during each change of the table
function createGroups() {

    var result = {};

    // Create any static groups    
    result['date-dd'] = result['date-mm'] = result['date-yyyy'] = 'date';

    // Create groups from dynamically added table rows
    var i = 1;
    jQuery("tr", "#table-id tbody").each(function() {

        for (j = 0; j < validateNames.length; ++j) {
            result[validateNames[j] + "-" + i] = 'fieldGroup_' + i;
        }

        i++;
    });    

    validator.groups = result;
}

put one errorElement: "span" which is used to display error on desired place. where username_group encode within span tag

$("#mc-embedded-subscribe-form").validate($.extend(settings, {     

groups: {
username: "FNAME LNAME" },
errorElement: "span" ,

errorPlacement: function(error, element) {
if (element.attr("name") == "FNAME" || element.attr("name") == "LNAME") { error.insertAfter("#username_group");
} else {
error.insertAfter(element);

} } }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM