Daniel
Daniel

Reputation: 138

jQuery Validation with depends

I would like to do validation which depends on other input value in same form.

$( "#step1" ).validate({
  rules: {
    weight: {
        required: true,
        max: $('#maxweight'),
        min: 1
    },
...

I was reading all documentation: jqueryvalidation.org, but I can not find anything about using other values from form to validate maximum value of other #id.

Thank you in advance for help.

--- EDIT ---

JS Fiddle, I would like to validate weight will depends on maxweight. Later I would like to do validate with if function:

if(maxweight == 10) {
    max: 10
}
else if(maxweight == 20) {
    max: 20
}

--- SOLUTION ---

Thanks all for help :) I did it this way: JS Fiddle

Upvotes: 1

Views: 13130

Answers (2)

kmas
kmas

Reputation: 6439

Here is an example :

$(".selector").validate({
  rules: {
    email: {
      depends: function(element) {
        // Do what you want to test
        return $("#contactform_email:checked");
      }
    }
  }
});

For what you want, here is a link that explains your problem jQuery validation - changing value of max at runtime

And here is the solution : http://jsfiddle.net/rUyAx/2/

$(document).ready(function() {
$("#step1").validate({
    rules: {
        weight: {
            required: true,
            //max: $("#maxweight").val(),
            min: 1
        }
    }
});

$("#submit").click(function(){
   $('#weight').rules("remove", "max");
   $('#weight').rules("add", {
     max: $('#maxweight').val()
   });
   $("#step1").submit();
});

});

(I have added an id to your submit button.)

Upvotes: 2

Anto Subash
Anto Subash

Reputation: 3215

try this. this will validate your weight based on the maxweight.

$("#step1").validate({
        rules: {
            weight: {
                required: true,
                min: 1,
                depends:function(element){
                    return  $(element).val() < $("#maxweight").val();
                }            
            }
        }
    });

Upvotes: 2

Related Questions