jQuery Validation plugin custom method. Multiple parameters

人盡茶涼 提交于 2019-12-30 01:37:09

问题


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.

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" }
            }
        });
});

回答1:


Javascript arrays:

[value1,value2,value3]

SO your code might be:

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



回答2:


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

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

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


来源:https://stackoverflow.com/questions/1366858/jquery-validation-plugin-custom-method-multiple-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!