如何使用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]
}
}
});
我无法理解负责替换$ .validator.format中的{0}和{1}的原因.以及如何传递这些参数?
I cannot comprehend what is responsible for replacing {0} and {1} in '$.validator.format'. And how to pass those parameters?
更新:
这是我收到的消息:
申请人的年龄必须大于真实年龄,小于[对象 HTMLInputElement]岁
Applicants must be older than true and younger than [object HTMLInputElement] years of age
推荐答案
我无法理解负责替换
'$.validator.format'
中的{0}
和{1}
的原因.以及如何传递这些参数?
I cannot comprehend what is responsible for replacing
{0}
and{1}
in'$.validator.format'
. And how to pass those parameters?
在上面的示例中,{0}
代表第一个参数,{1}
代表第二个参数.参数分别为[5, 6]
,并且消息中的此类自动替换由插件自动处理.
In your example above, {0}
represents the first parameter and {1}
represents the second parameter. The parameters are [5, 6]
respectively and the automatic replacement of such within the message is handled automatically by the plugin.
因此,编写自定义方法时,您不需要做任何特别的事情.如果您将三个参数传递给您的方法...
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]
...然后您将具有用于自定义消息的{0}
,{1}
和{2}
,分别代表参数的每个值.
...then you'll have {0}
, {1}
, and {2}
available for your custom message, representing each value of the parameters respectively.
它可以正常工作.
如果出了什么问题,那么除了:
If there is something going wrong, then it's not obvious from your OP aside from:
该方法称为
max-numeric
,但是您要在.validate()
方法的rules对象中引用min-numeric
.
The method is called
max-numeric
, but you're referencingmin-numeric
in the rules object of the.validate()
method.
只要在max-numeric
旁边有两个参数,示例就可以工作.
As long as you have two parameters next to max-numeric
, then your example would work.
max-numeric: [5, 6]
这篇关于如何使用jQuery.validator占位符来自定义错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!