3

Good morning

I have been using the jquery validate function for a while and it's great. However, wondering if its possible to have the group error label only clear out once BOTH (or 3 or 4) elements in the group are correct. For example, if I have an empty first and last name in a group, the error goes away once I type in just the first name. I know I can disable the onfocusout function, but I would rather not. Thank you!

Ortal
  • 333
  • 1
  • 7
  • 21

1 Answers1

5

This does indeed look like a bug in jQuery validate (you could file a bug here). To get around it you could define a very specific custom rule:

$.validator.addMethod("name", function(value, element) {
    return $("#firstname").val() !== '' && $("#lastname").val() !== '';
}, "Name is required");

And still use the groups functionality:

$("form").validate({
    groups: {
        name: "firstname lastname"
    },
    firstname: "name",
    lastname: "name",
    errorPlacement: function(error, $element) {
        var name = $element.attr("name");
        if (name === "firstname" || name === "lastname") {
            error.insertAfter("#name");
        } else {
            error.insertAfter($element);
        }
    }
});

The custom rule feels unmaintainable and hacky, since if your field ids change, your validation will break. However, it does get rid of the problem.

Here's an example: http://jsfiddle.net/Rqbws/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • hm, i see. however how would this work when i have several rules that apply to each field (regex, custom, etc) in a group? – Ortal Jun 15 '11 at 17:57
  • @Ortal: You're right, it isn't a robust solution. I'll try to come up with something better. It's unfortunate that jQuery validate doesn't handle this automatically. – Andrew Whitaker Jun 16 '11 at 13:12