0

I'm using meio mask (old site)

I want to be able to mask an input so it allows me to enter a percentage value between 0 and 100, integers only.

I've tried this:

$.mask.rules = $.extend($.mask.rules, {
    '%': /0|[1-9][0-9]?|100/,
});

$.mask.masks = $.extend($.mask.masks, {
    "percentage": { mask: "%%%" }
});

But it doesn't work. How can I write a proper rule to achieve this?

Matías Cánepa
  • 5,770
  • 4
  • 57
  • 97

1 Answers1

0

The following code should do the trick, the rule matches any number between 0 and 100, including leading zeros. The ? in [1-9]?[0-9] allows for single-digit numbers (e.g., "5") and double-digit numbers (e.g., "23"), but not triple-digit numbers (e.g., "105"). The | separates the two possible matches for 100.

$.mask.rules = $.extend($.mask.rules, {
    '%': /[1-9]?[0-9]|100/
});

This sets the mask to "###%", which allows up to three digits followed by a percent symbol. The rules option specifies the % rule we defined earlier, so it will only allow valid percentage values.

$.mask.masks = $.extend($.mask.masks, {
    "percentage": { mask: "###%", rules: { '%': /[1-9]?[0-9]|100/ } }
});
Toxic
  • 11
  • 2