delliottg
delliottg

Reputation: 4140

How to pass variables to jQuery validation

Building off of this SO question, I'm trying to pass two variables to a custom validator method. Using console.log I can see that the upper & lower ranges are defined in the HTML, but are not being passed correctly to the options, instead I'm getting NaN instead.

The problem seems to be that the values of the two text boxes are not defined or set yet (when they're sent in the validation rules below), but are when they arrive to the validator (this is just a guess, and I haven't been able to come up with a method to sniff their values prior to the validation attempt). So if I log them inside the validator method, they show up fine, but if I pass them as variables, they show up as NaN inside the PCBID object (Chrome browser):

Object {PCBID: Object}
    PCBID: Object
        lower: NaN
        upper: NaN
    __proto__: Object
    __proto__: Object

Here's the validator, there are other rules set to prevent anything from integers being entered, so that shouldn't be the problem:

//this validator checks to make sure the user has entered the PCBIDs in 
//the correct order in the range form.
$.validator.addMethod("highLowCheck", function (value, element, options)
{
console.log("Inside highLowCheck validator");
console.log(parseInt($('#pcbid_range_lower').val(),10)); //shows expected values
console.log(parseInt($('#pcbid_range_upper').val(),10)); //shows expected values

console.log(options.PCBID.upper); //NaN
console.log(options.PCBID.lower); //NaN
//evaluates to false because NaN is falsey
console.log(options.PCBID.upper > options.PCBID.lower); 
console.log("Done logging");
return options.PCBID.upper > options.PCBID.lower;
}
);

Here are the variables I'm trying to pass:

            pcbid_range_upper: {
            required: true,
            digits: true,
            rangelength: [3, 6],
            highLowCheck:
            { PCBID:
                {
                    //this doesn't work                        
                    lower: parseInt($('#pcbid_range_lower').val(),10), 
                    upper: parseInt($('#pcbid_range_upper').val(),10)
                }
            },

If I pass in primitive values like this:

            highLowCheck:
            { PCBID:
                {
                    lower: 1000, //works
                    upper: 2000
                }
            },

This method works, but it's not very useful because users can enter any value they like so I have to be able to pass them in as variables. I also need this to work with variables because I need to call it from more than one validation routine, otherwise I'd just use the variables in the validator directly (as I was before the need for more than one form to use the validator).

In case it's useful, here is the HTML for the two inputs:

<div data-role="fieldcontain" data-controltype="textinput" class="pcbid_selections" tabindex="2">
    <label for="pcbid_range_lower">Starting PCBID *</label>
    <input name="pcbid_range_lower" id="pcbid_range_lower" class="create_group" placeholder="52759" value="" type="text" data-mini="true" />
</div>
<div data-role="fieldcontain" data-controltype="textinput" class="pcbid_selections" tabindex="3">
    <label for="pcbid_range_upper">Ending PCBID *</label>
    <input name="pcbid_range_upper" id="pcbid_range_upper" class="create_group" placeholder="52769" value="" type="text" data-mini="true">
</div>

The Question: How can I pass variables inside a rule to a custom validator?

EDIT:

The Solution: with thanks to @Sparky & Mathletics

The validator method was changed to only receive the strings of the names of the two variables I wanted to pass, not their contents. Then using @Mathletic's suggestion, I simply put them into jQuery variable form inside the validator:

//this validator checks to make sure the user has entered the PCBIDs in the 
//correct order in the range form.
$.validator.addMethod("highLowCheck", function (value, element, options){
return parseInt($('#' + options.PCBID.upper).val(), 10) > 
       parseInt($('#' + options.PCBID.lower).val(), 10);
}
);

And called them from the rules like so:

highLowCheck:
    {
        PCBID:
        {
            lower: 'pcbid_range_lower',
            upper: 'pcbid_range_upper'
        }
    },

Just an FYI to anyone who finds this, I tried passing in the pound sign ("#") with the strings from the rules (EG: '#pcbid_range_lower'), but that didn't seem to work. This method does, and you can just prepend the "#" in the validator method instead which works well.

Upvotes: 1

Views: 7484

Answers (1)

Sparky
Sparky

Reputation: 98718

Quote OP:

"The Question: How can I pass variables inside a rule to a custom validator?"

Declared within .validate()...

rules: {
    myField: {
        customMethod: [1, "two", 3, "foo"]
    }
}

customMethod defined...

$.validator.addMethod("customMethod", function (value, element, options) {
    console.log(options[0]);      // <- 1
    console.log(options[1]);      // <- "two"
    console.log(options[2]);      // <- 3
    console.log($('[name=' + options[3] + ']').val()); // <- value of field named "foo"
    console.log(value);      // <- the value of "myField"
    console.log(element);    // <- the "myField" object
    // your function
}, "Custom message with options used as {0}, {1}, {2}, {3} etc.");

DEMO: http://jsfiddle.net/pupggbu7/

Documentation: http://jqueryvalidation.org/jQuery.validator.addMethod/

Upvotes: 5

Related Questions