jQuery 验证插件自定义方法。多个参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1366858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:17:46  来源:igfitidea点击:

jQuery Validation plugin custom method. Multiple parameters

jqueryjquery-validate

提问by BuzzBubba

I'm trying to use a custom validator with jQuery Validation plugin. However, I'm unsure how are you supposed to pass multiple arguments to a validation method? I've tried using (2,3), curly braces and combinations, but I have failed.

我正在尝试将自定义验证器与 jQuery 验证插件一起使用。但是,我不确定您应该如何将多个参数传递给验证方法?我试过使用 (2,3)、花括号和组合,但我失败了。

This is the code - ???? marks the area I need info about:

这是代码 - ???? 标记我需要有关以下信息的区域:

$(document).ready(function() {
        jQuery.validator.addMethod("math", function(value, element, params) {
            return this.optional(element) || value == params[0] + params[1];
        }, jQuery.format("Please enter the correct value for {0} + {1}"));

        $("#form_register").validate({
            debug: true,
            rules: {
                inputEl: { required: true, math: ???? }
            },
            messages: {
                inputEl: { required: "Required", math: "Incorrect result" }
            }
        });
});

回答by jantimon

Javascript arrays:

Javascript 数组:

[value1,value2,value3]

SO your code might be:

所以你的代码可能是:

inputEl: { required: true, math: [2, 3 ,4 , 5] }

回答by Ben Foster

You can also pass a normal JavaScript object as a parameter which I personally find easier to work with:

你也可以将一个普通的 JavaScript 对象作为参数传递,我个人认为它更容易使用:

jQuery.validator.addMethod("myRule", function (value, element, options) {
    return value === options.data;
}, "My Rule says no!");

$("#input").rules("add", { myRule: { data: "foo" } });