Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validation - Change min max number checking at runtime

Can I change the min, max of a number's validation at runtime ?

I use jQuery validation plugin.

My simplified layout and structure to demonstrate how it should work. when I change the value of max range the max range's validation of the field number has to be changed too.

jsFiddle: http://jsfiddle.net/nXqd/qC2Ya/3/

Thanks

like image 553
Dzung Nguyen Avatar asked Jul 01 '26 07:07

Dzung Nguyen


2 Answers

Using this answer from another SO post as a guide I was able to change your code and get this to work.

// Bind initial rule;
bindRangeRule(1, 2);

$("input[name='change-range']").on("keyup", function() {
    var value = $(this).val();

    // add some validation here off course to ensure only numbers are accepted.
    // You can do that by checking the event.keyCode values I believe.
    // If an invalid value was specified you can throw an alert
    // or simply clear the input field and return false. Or similar.

    // re-bind range rule
    bindRangeRule(1, parseInt(value));
});

function bindRangeRule(from, to) {
    var settings = $('form').validate().settings;

    delete settings.rules.number;

    settings.rules.number = {
        required: true,
        range: [from, to]
    }
};
like image 158
Nope Avatar answered Jul 02 '26 22:07

Nope


Updated demo: http://jsfiddle.net/techfoobar/qC2Ya/5/


You can do this by specifying min and max options in your validation rules:

For ex:

$("#myform").validate({
  rules: {
    field: {
      required: true,
      min: 13
    }
  }
});

API Docs:

http://docs.jquery.com/Plugins/Validation/Methods/min#value

http://docs.jquery.com/Plugins/Validation/Methods/max#value

like image 41
techfoobar Avatar answered Jul 02 '26 20:07

techfoobar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!