Skip to content

JavaScript: dynamically changing values of data range rule

I have an input field that either allows negative and positive numbers, or only positive numbers based on a value of a select.

When changing the value of the select option, I’m trying to modify the rule of the input field like this:

const id = '#myId';
$(id).attr("data-val-range-min", -10000);
removeRules(id);
addRules(id);
$(id).change(); // trying to trigger the validation of the rule

The removeRules is a function:

let removeRules = function removeRules(field) {
    $(field).rules('remove');
}

And so is the addRules:

let addRules = function addRules(field) {
    let $field = $(field);
    
    if ($field.attr("data-val-required")) {
        $field.rules("add", {
            required: true,
                messages: {
                    required: $field.attr("data-val-required")
                }
        });
    }
    
    if ($field.attr("data-val-number")) {
        $field.rules("add", {
            number: true,
                messages: {
                    number: $field.attr("data-val-number")
                }
        });
    }

    if ($field.attr("data-val-range")) {
        $field.rules("add", {
            range: [$field.attr("data-val-range-min"), $field.attr("data-val-range-max")],
                messages: {
                    range: $field.attr("data-val-range")
            }
        });
    }
}

When I change the select in the UI, the data-val-range-min attribute is set correctly, but the rule is not reapplied.

Only when I manually click into the input-field and deselect it again, the rule is applied…

What am I doing wrong here?

Thanks in advance

Answer

Only when I manually click into the input-field and deselect it again, the rule is applied…

There’s a validation trigger you expect that isn’t part of the plugin.

By default, this plugin triggers validation on:

  • onfocusout – when you leave an element
  • onkeyup – when you’re typing inside a text box
  • onclick – interactions with radio, checkbox, and select

Adding and removing the rules though is not enough… you’ll also need to force a validation test after adding or removing the rule.

Simply call the .valid() method on the element or form when you want to programmatically force validation. Since your OP contains zero HTML markup or working demo, I cannot be more specific with a solution.