动态jQuery使用AddMethod基于元素验证错误消息 [英] Dynamic jQuery Validate error messages with AddMethod based on the element
本文介绍了动态jQuery使用AddMethod基于元素验证错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个自定义AddMethod到jQuery Validate,如:
Let's say I have a custom AddMethod to jQuery Validate like:
$.validator.addMethod('min-length', function (val, element) {
// do stuff
// the error message here needs to be dynamic
}, 'The field cannot be less than than '
+ element.attr('data-min') + // it is within the closure, but it can't grab it
' length.');
我无法找到一种方法来获取元素变量问题,并从中获取任何价值。我在这里缺少什么?
I can't figure out a way to get the element variable in question, and get any values from it. What am I missing here?
推荐答案
从查看验证器源代码,我认为应该这样做:
From looking at the validator source code, I think this should do it:
$.validator.addMethod('min-length', function (val, element) {
return this.optional(element) || val.length >= $(element).data('min');
}, function(params, element) {
return 'The field cannot be less than than ' + $(element).data('min') + ' length.'
});
在原始代码中,消息字符串不在闭包内;闭包是 addMethod
的第二个参数,错误信息是第三个参数。
In your original code, the message string is NOT within the closure; the closure is the 2nd argument to addMethod
, the error message is the 3rd argument.
这篇关于动态jQuery使用AddMethod基于元素验证错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文