Mi Ro
Mi Ro

Reputation: 760

jquery validate dynamically change min value

I have validation on form field which works ok. When I click on element in page, I take value of it, put it into form field and I want to change min value in validation to this value I tried rules method but it looks it is not working, but no error is shown

this is my validation call

$('form').validate({
lang: 'sk',
rules: {
  'payment[amount]': {
    min: 1
  }
},
highlight: function(element) {
  $(element).parent().addClass('state-error');
},
unhighlight: function(element) {
  $(element).parent().removeClass('state-error');
}

});

and this is my function running when I click on element

 $( "rewardbox" ).click(function() {
  $val = $( this ).children("amount").text();
  $num = parseInt($val);
  $("#payment_amount").val($num);
  $('html, body').animate({ scrollTop: 0 }, 'slow');

  $( "#form" ).rules( "remove", "min" );
  $("#form").rules("add", {
      'payment[amount]':{
      min: function ()  { return $("#payment_amount").val()  }
    }
  });
});

I tried to put as min value directly my variable $num but no luck

how this should work?

Upvotes: 0

Views: 2378

Answers (2)

Sparky
Sparky

Reputation: 98738

When using the .rules() method, it does not get attached the form element. It only gets attached to the input field where you're attaching the new rule.

Since you would attach .rules() to the input itself, you do not declare the input name inside of it. As per the docs, just key:value pairs of the rules being added or removed and/or a custom messages object.

$("#payment_amount").rules("remove", "min");
$("#payment_amount").rules("add", {
    min: 2 
});

Please refer to usage examples in the documentation.

Upvotes: 1

Shiva
Shiva

Reputation: 567

have you placed validations after click function ..

i mean

$(document).ready(function(){

// click function (in click function append required value to a hidden field)

// then add validation (in validation min: function ()  { return $("#payment_amount").val()  } this will work )

});

Upvotes: 0

Related Questions