Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to use jQuery Validate to validate an age is between two years in a metadata tag, and specify the years as parameters.

The problem I have is I can't pass the parameters as an object so I don't know how to access them in the error message (and can't find any documentation on it).

HTML

<input type="text" name="dob" id="dob" validAge="[17,66]" />


JavaScript

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


The output for {0} is my parameter string and {1} is the HTTPInputElement.


I've now written a minAge and maxAge function to get around this, but I'd still be keen to get a resolution to this.

like image 396
Delorian Avatar asked Apr 11 '14 00:04

Delorian


3 Answers

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/

like image 161
John B Avatar answered Nov 14 '22 21:11

John B


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'));
like image 2
NMC Avatar answered Nov 14 '22 21:11

NMC


You can't find documentation, because you can't do it.

Using the jQuery Validation plugin and a custom method, you cannot declare the validAge rule inline when you need to pass parameters.

<input type="text" name="dob" id="dob" validAge="[17,66]" />

Only certain rules that can be declared with a boolean (can be declared as class names), or rules that are also HTML5 validation attributes can be declared inline.

For your custom method with parameters, it must (can) be declared within the .validate() method...

$('#myform').validate({
    // your options, rules, etc,
    rules: {
        dob: {
            validAge: [17,66]
        }
    }
});

EDIT:

As pointed out by @John Bubriski, this should be working. The OP was not accessing the parameters correctly in his custom method.

The OP was using JSON.parse...

var range = JSON.parse(params);

which gives a syntax error in the console since it's not recognizing params as a valid JSON string. Parsing the params variable is not necessary.

The parameters are passed into the function as params, so they can be accessed directly as params[0], params[1], etc.

jQuery.validator.addMethod('validAge', function (value, element, params) {
    value = eLifeViewModel.age();
    if (value === '') {  // <- You do NOT need this! 
    /* Use the "required" rule instead of this conditional */
        return false;
    }
    return value > params[0] && value < params[1];
}, $.format('Applicants must be older than {0} and younger than {1} years of age'));
like image 1
Sparky Avatar answered Nov 14 '22 23:11

Sparky