14

Is there a way to pass dynamic parameters into a custom jquery validate method? Specifically, I was looking for a way to compare 2 controls and would like to pass one to the other's validate method for comparison.

Here is what I currently have:

 //Add method
 $.validator.addMethod("lowerInt", function(value, element, params) {
            alert('inside method');
            if (isNaN(parseInt(params)))
                return true;
            else
                return parseInt(value) < parseInt(params);
        }, $.validator.format("Please enter a number smaller than {0}")); 

 //Set validation
 $("#form1").validate({
     rules: {
        lowInt: {
            required: true,
            integer: true,
            lowerInt: 8 //I would like to pass a dynamic value here
        }
     }
 });

If I run it as above, it works as it should. If I change the 8 passed in to lowerInt to $('#highInt').val(), it seems to set the value for the lowerInt function only once and never update it. I realize that I can get the value inside of the method by calling $('#highInt').val(), but I would like to pass the value instead if at all possible.

2 Answers 2

16

I would pass in a selector, like this:

//Add method
$.validator.addMethod("lowerInt", function(value, element, params) {
  var hi = typeof params[0] == "string" ? 
           parseInt($(params[0]).val(), 10) :
           params[0];
  if (isNaN(hi))
    return true;
  else
    return parseInt(value) < hi;
}, $.validator.format("Please enter a number smaller than {0}")); 

//Set validation
$("#form1").validate({
  rules: {
    lowInt: {
        required: true,
        integer: true,
        lowerInt: '#highInt'
    }
  }
});

This version will take either a number or a selector, making it as flexible as possible.

Sign up to request clarification or add additional context in comments.

1 Comment

Will this output the message 'Please enter a number smaller than #highInt'? I'd love to be able to give the user something more friendly.
6

Make the parameter a function.

$("#form1").validate({
     rules: {
        lowInt: {
            required: true,
            integer: true,
            lowerInt: function(){ return $('#highInt').val(); }
        }
     }
 });

Then you call the function in the validate method something like

var high = params[0]();

Comments

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.