【问题标题】:How to only hide the default error message in jquery validate?如何仅在 jquery validate 中隐藏默认错误消息?
【发布时间】:2019-12-11 16:27:18
【问题描述】:

我有几个字段,对于出生日期字段,我想在需要时隐藏错误消息,但显示所有其他错误消息。我有以下隐藏所有错误消息的代码:

<input type="number" id="DayOfBirth" min="1" max="31" class="input error" name="DayOfBirth" placeholder="DD" aria-invalid="true">

JS:

rules = {
    DayOfBirth: required
};
messages = {
    DayOfBirth: "Required field is missing: Day of Birth"
};
$('#myForm').validate({
    rules: rules,
    messages: messages,
    errorPlacement: function (error, element) {
        if (element.attr("name") == "DayOfBirth") {
            error.hide();
        }
        else {
            error.insertAfter(element);
        };
    },
})

所以基本上我想隐藏默认错误消息(“缺少必填字段:出生日期”),但保留最小值和最大值的消息,我该怎么做?

【问题讨论】:

  • 打印时错误的 HTML 是什么?
  • @Morris 在必填的情况下,错误 html 为“必填字段缺失:出生日期”;对于负数或大于 31 的值,消息应为“值必须大于或等于 1”或“值必须小于或等于 31”
  • @Sparky 我在 html 中定义了 min 和 max 值,因此如果用户输入了错误的值,jQuery-validate 将不会像我展示的那样将其拾取并显示默认错误消息在我的最后一条评论中?
  • 哦,是的,我现在明白你的意思了。是的,jQuery Validate 也会自动获取 HTML5 内联验证属性。更新答案...相同的解决方案。

标签: jquery jquery-validate


【解决方案1】:

你的整个问题都在这里......

messages = {
    // same message for ALL rules on this field
    DayOfBirth: "Required field is missing: Day of Birth"
};

这为名为@9​​87654324@ 的字段上的所有规则定义了一条自定义消息。

那么就仅基于字段名称有条件地显示规则而言,这实际上工作得很好......

errorPlacement: function (error, element) {
    if (element.attr("name") == "DayOfBirth") { 
        error.hide();  // hide ALL messages for the matching field
    }
    else {
        error.insertAfter(element);
    };
},

但是,这将隐藏名为 DayOfBirth 的字段的所有消息。

换句话说,您为一个字段的所有规则设置了相同的自定义消息,然后隐藏了同一字段的所有/所有消息。没有意义。


如果您只想在一个特定字段上隐藏required 规则的消息,那么只需将其自定义消息设置为空白...

$(document).ready(function() {

    $('#myForm').validate({
        rules: {
            foo: {
                required: true,
                minlength: 5
            },
            bar: {
                required: true
            }
        },
        messages: {
            foo: {
                required: "",  // show nothing
                minlength: "foo too short"
            },
            bar: {
                required: "bar is required"
            }
        }
    })

});

演示:jsfiddle.net/e8jwLfb2/


就像 OP 在他的设置中一样;通过 .validate() 方法声明的混合规则以及一些内联 HTML5 属性。这是相同的解决方案,因为自定义消息是通过插件定义的:

演示 2:jsfiddle.net/bLn169h2/

当使用messages 对象时,您可以在字段上为每个规则设置自定义消息...

messages: {
    foo: {
        required: "custom required message for foo field",
        minlength:  "custom minlength message for foo field"
    }
}

整个字段的OR...

messages: {
    foo: "custom message for all rules on foo field"
}

无论如何或在何处声明每条规则,此自定义消息都将被覆盖。因此,在您的情况下,您在字段名称上定义了一条自定义消息,它将覆盖该字段上所有规则的所有验证消息。然后你在errorPlacement 中有一个条件函数,它隐藏了整个字段的“验证消息”。同样,在哪里声明规则并不重要,因为所有规则和消息都来自 jQuery Validate 插件。

【讨论】:

  • 第一个解决方案更接近我的实际解决方案,绝对有帮助,谢谢!
猜你喜欢
  • 2016-09-11
  • 1970-01-01
  • 2018-12-01
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多