Warm tip: This article is reproduced from serverfault.com, please click

Knockout JS Count only numbers in maxLength attribute

发布于 2020-12-18 02:50:07

Is there a way to manipulate maxLength attribute to count only numbers? I have seen this code MyObservable.replace(/[^0-9]/g, '').length that can only count numbers but I don't know where to put it. Or any better Idea. Thanks

Questioner
MCMXCVIII
Viewed
1
Sam 2020-12-21 16:45:05

You'll need to use a custom binding if you want to limit to a certain amount instead of the length of a string. There's 2 options, with one you remain with an input="text" and the second being an input="number"

The difference that with the first you'll need to include a regex somewhat like your example into the following piece of code, where with the second option the browser has already taken care of that, I'll leave it up to you where you want to go with this.

ko.bindingHandlers.maxValue = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var valueObservable = valueAccessor();

        ko.utils.registerEventHandler(element, "change", function () {
            var value = Number(element.value);
          if (value >= 0) {
            if (value > allBindings().maxAmount) {
                value = allBindings().maxAmount;
            }
            element.value = value;
            valueObservable(value);
          }
        });
    },
};

var ViewModel = function ()
{
    var self = this;
  self.value = ko.observable();
};

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input type="number" data-bind="maxValue: $root.value, maxAmount: 100" />