jQuery Validator自定义方法 [英] jQuery Validator custom method
问题描述
请您看看这个 http://jsbin.com/osolo/吗?
如果您以最小年龄而不是数字输入字母,然后点击提交,则使用自定义验证方法中的正则表达式使用jquery验证程序验证此验证,此方法有效,但我现在正在寻找使其更具动态性的方法.
If you enter a letter in Min Age rather than a number then hit submit this validates using jquery validator using a regular expression in a custom validation method, this works but i'm now looking to make it a little more dynamic.
在自定义验证方法行
var data = $(element).metadata();
从要验证的元素中获取元数据,我想做的就是使用
grabs meta data from the element being validated, what i would like to do is use the
data.validateOptions.regex
作为要测试的正则表达式(我看不到这是一个问题),我可以看到一个问题是,如果该字段未通过验证,而不是使用在调用时提供的消息>
as the regex to test with (i can't see this being a problem), what i can see being a problem is that if the field doesn't validate, rather than using a message that is supplied when calling
jQuery.validator.addMethod(name, method, message)
我想使用
data.validateOptions.message
作为自定义方法中的错误消息,有人可以向我指出正确的方向吗?
as the error message from within the custom method, can anyone point me in the right direction please?
谢谢
OneShot
推荐答案
我认为Alex的答案将不起作用,因为JS中的字符串是不可变的.
I think Alex's answer won't work because strings are immutable in JS.
虽然很近.从Alex的代码开始,如果创建一个包含数据对象(或仅一个消息字符串)以及返回消息的函数的闭包,则可以将该函数作为第三个参数传递给addmethod调用. 像这样:
It's close though. Starting with Alex's code, if you create a closure containing the data object (or just a message string) and also a function returning the message, you can pass the function as the third argument to the addmethod call. Like so:
(function() {
var data = {};
var messager = function() {
return data.validateOptions.message;
};
jQuery.validator.addMethod("perorgproperty", function(value, element) {
debugger;
//alert('testing perorgproperty');
data = $(element).metadata();
return this.optional(element) || /^\d+$/i.test(value);
}, messager);
})();
这篇关于jQuery Validator自定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!