简体   繁体   English

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

[英]How to customize error message using jQuery.validator placeholders?

I'm trying to add custom form validators. 我正在尝试添加自定义表单验证器。 And I'm stuck with message customizing issue. 而且我遇到了消息自定义问题。

Let's say I want to check if field value does not exceeds max allowed value. 假设我要检查字段值是否未超过最大允许值。 I know that 'Validation Plugin' has a "max" validator already - this is just for sample: 我知道“验证插件”已经具有“最大”验证器-这仅用于示例:

$.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]
        }
    }
});

I cannot comprehend what is responsible for replacing {0} and {1} in '$.validator.format'. 我无法理解是什么负责替换$ .validator.format中的{0}和{1}。 And how to pass those parameters? 以及如何传递这些参数?

UPDATE: 更新:

Here is the message I get: 这是我收到的消息:

Applicants must be older than true and younger than [object HTMLInputElement] years of age 申请人必须大于真实年龄且小于[object HTMLInputElement]岁

I cannot comprehend what is responsible for replacing {0} and {1} in '$.validator.format' . 我无法理解是什么负责替换'$.validator.format' {0}{1} And how to pass those parameters? 以及如何传递这些参数?

In your example above, {0} represents the first parameter and {1} represents the second parameter. 在上面的示例中, {0}代表第一个参数, {1}代表第二个参数。 The parameters are [5, 6] respectively and the automatic replacement of such within the message is handled automatically by the plugin. 参数分别为[5, 6] ,消息中的此类自动替换由插件自动处理。

So when writing a custom method, there is nothing special you'll need to do. 因此,编写自定义方法时,您不需要做任何特别的事情。 If you pass three parameters into your method... 如果您将三个参数传递给方法...

customMethod: [34, 50, 10]

...then you'll have {0} , {1} , and {2} available for your custom message, representing each value of the parameters respectively. ...那么您将获得{0}{1}{2}的自定义消息,分别代表参数的每个值。

It just works. 它只是工作。


If there is something going wrong, then it's not obvious from your OP aside from: 如果出了什么问题,除了以下几点,从您的OP中看不出来:

The method is called max-numeric , but you're referencing min-numeric in the rules object of the .validate() method. 该方法称为max-numeric ,但是您要在.validate()方法的rules对象中引用min-numeric

As long as you have two parameters next to max-numeric , then your example would work. 只要在max-numeric旁边有两个参数,您的示例就可以工作。

max-numeric: [5, 6]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM