jQuery验证-组及其标签 [英] jquery validate - groups and their labels

查看:118
本文介绍了jQuery验证-组及其标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好

我已经使用了一段时间的jquery validate函数,它很棒.但是,想知道是否只有在组中的两个(或3个或4个)元素正确之后才可以清除组错误标签.例如,如果我的组中的姓氏和名字都为空,则只要输入名字,该错误就会消失.我知道我可以禁用onfocusout功能,但我不愿意.谢谢!

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!

推荐答案

这确实看起来像是jQuery验证中的错误(您可以提交错误此处).要解决这个问题,您可以定义一个非常具体的自定义规则:

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");

并仍然使用groups功能:

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

自定义规则难以维护且难以破解,因为如果更改字段id,您的验证就会中断.但是,它确实解决了这个问题.

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.

这里是一个示例: http://jsfiddle.net/Rqbws/

这篇关于jQuery验证-组及其标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆