3

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

2
  • 3
    Can you post your current implementation, the relevant script and html? Maybe even a fiddle on jsfiddle.net is possible? Commented Sep 18, 2012 at 12:16
  • @FrançoisWahl added the jsfiddle :) Commented Sep 18, 2012 at 12:33

2 Answers 2

7

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]
    }
};
Sign up to request clarification or add additional context in comments.

1 Comment

demo returns 404
3

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

2 Comments

The OP is looking to change this at runtime, e.g. when some event happens
sorry for being too quick, I post my jsfiddle so you can take a look at it more easier,

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.