如何使用 jQuery.validator 占位符自定义错误消息?

How to customize error message using jQuery.validator placeholders?

我正在尝试添加自定义表单验证器。我被消息自定义问题困住了。

假设我想检查字段值是否不超过最大允许值。 我知道 'Validation Plugin' 已经有一个 "max" 验证器 - 这只是为了示例:

$.validator.addMethod("max-numeric", function(value, element, param) {
    var maxValue = $(element).attr("data-max");
    return (!maxValue) || maxValue >= value;
}, $.validator.format('Applicants must be older than {0} and younger than {1} years of age'));

$("#data-form").validate({
    rules: {
        "form.params1.p4":
        {
            "min-numeric": [5, 6]
        }
    }
});

我无法理解是什么负责替换“$.validator.format”中的 {0} 和 {1}。以及如何传递这些参数?

更新:

这是我收到的消息:

Applicants must be older than true and younger than [object HTMLInputElement] years of age

I cannot comprehend what is responsible for replacing {0} and {1} in '$.validator.format'. And how to pass those parameters?

在您上面的示例中,{0} 代表第一个参数,{1} 代表第二个参数。参数分别为[5, 6],消息中的此类参数的自动替换由插件自动处理。

因此,在编写自定义方法时,您不需要做任何特别的事情。如果您将三个参数传递给您的方法...

customMethod: [34, 50, 10]

...然后您将有 {0}{1}{2} 可用于您的自定义消息,分别代表参数的每个值。

它很管用。


如果出现问题,那么从您的 OP 来看并不明显,除了:

The method is called max-numeric, but you're referencing min-numeric in the rules object of the .validate() method.

只要 max-numeric 旁边有两个参数,您的示例就可以工作。

max-numeric: [5, 6]