开发者

jquery validate - groups and their labels

开发者 https://www.devze.com 2023-03-12 23:25 出处:网络
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) element

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. 开发者_如何学GoFor 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!


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/

0

精彩评论

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

关注公众号