jQuery Validate custom validator with multiple params in metadata tag and message

This does work, at least in the latest jQuery/Validate. Here is a fiddle showing some custom validators, 3 of which take an array of parameters: http://jsfiddle.net/jbubriski/YQgEq/120/

Here is one of the examples that takes string params. Instead of saying data-rule-customname="true", you specify the parameters data-rule-customname='["string",1,2,3]'.

(Note the flipping of quotes... using single quotes to denote the strings doesn't seem to work. Use double quotes)

Markup:

<div>
    Custom 3 (Requires 'pig' or 'mouse'): <input type="text" id="custom3" name="custom3" data-rule-required="true" data-rule-customv3='["pig","mouse"]' data-msg-customv3="Enter a cool animal name!" />
</div>

JS:

jQuery.validator.addMethod("customv3", function(value, element, params) {
    if (this.optional(element))
        return true;

    for (var i = 0; i < params.length; i++)
        if (value == params[i])
            return true

    return false;
}, jQuery.validator.format("Please enter one of the following values: {0} {1}"));

The only issue with the above example is that I'm not sure if there is a way to dynamically generate the error message if you're expecting n parameters. The current code works fine, but assumes 2 parameters.

I also have a blog post that details some other aspects of using attribute-based validation: http://johnnycode.com/2014/03/27/using-jquery-validate-plugin-html5-data-attribute-rules/


The params variable doesn't return a string but an object.

Try to pass the range directly from params :

jQuery.validator.addMethod('validAge', function (value, element, params) {
        value = eLifeViewModel.age();
        if (value === '') {
            return false;
        }
        return value > params[0] && value < params[1];
    }, $.format('Applicants must be older than {0} and younger than {1} years of age'));