32

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

2 Answers 2

46

Javascript arrays:

[value1,value2,value3]

SO your code might be:

inputEl: { required: true, math: [2, 3 ,4 , 5] }
Sign up to request clarification or add additional context in comments.

Comments

26

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

1 Comment

One drawback of this is that then you cannot use parameterized error messages. This plugin automatically formats error message with given value or parameters, so you can have error message "Please select more than {0} items" and it will automatically replace "{0}" with input's value (of with first parameter). So if parameter is an object, it won't work. And having multiple parameters you can have more user friendly error messages, for example in range situation, where params[0] could be lower range value nad params[1] upper range value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.