敲除最小/最大验证不起作用

时间:2018-04-06 13:39:02

标签: javascript knockout.js knockout-validation

我正在使用我在https://github.com/jenkinsci/last-changes-plugin

找到的自定义绑定处理程序

将输入格式化为货币非常有效。但是,它也会阻止我的Knockout最小/最大验证工作。我需要1分钟和最多200分钟。有没有人为什么会这样?

自定义绑定

function formatCurrency(symbol, value, precision) {
    return (value < 0 ? "-" : "") + symbol + Math.abs(value).toFixed(precision).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
  }

  function rawNumber(val) {
    return Number(val.replace(/[^\d\.\-]/g, ""));
  }

  ko.bindingHandlers.currency = {
    symbol: ko.observable("$"),
    init: function (element, valueAccessor, allBindingsAccessor) {
      //only inputs need this, text values don't write back
      if ($(element).is("input") === true) {
        var underlyingObservable = valueAccessor(),
          interceptor = ko.computed({
            read: underlyingObservable,
            write: function (value) {
              if (value === "") {
                underlyingObservable(null);
              } else {
                underlyingObservable(rawNumber(value));
              }
            }
          });
        ko.bindingHandlers.value.init(element, function () {
          return interceptor;
        }, allBindingsAccessor);
      }
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
      var symbol = ko.unwrap(allBindingsAccessor().symbol !== undefined ? allBindingsAccessor().symbol : ko.bindingHandlers.currency.symbol),
        value = ko.unwrap(valueAccessor());
      if ($(element).is("input") === true) {
        //leave the boxes empty by default
        value = value !== null && value !== undefined && value !== "" ? formatCurrency(symbol, parseFloat(value), 2) : "";
        $(element).val(value);
      } else {
        //text based bindings its nice to see a 0 in place of nothing
        value = value || 0;
        $(element).text(formatCurrency(symbol, parseFloat(value), 2));
      }
    }
  };

ViewModel observable

self.PriceAdvanced = ko.observable("").extend({ required: true, min: 1, max: 200 });

HTML

<input class="form-control max225" type="text" id="PriceAdvanced" name="PriceAdvanced" data-bind="currency: PriceAdvanced" size="23" placeholder="$0.00" />

1 个答案:

答案 0 :(得分:0)

找到答案here,它完美无缺:

  

首先,创建自定义绑定,例如......

ko.bindingHandlers.yourBindingName = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called when the binding is first applied to an element
        // Set up any initial state, event handlers, etc. here
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // This will be called once when the binding is first applied to an element,
        // and again whenever any observables/computeds that are accessed change
        // Update the DOM element based on the supplied values here.
    }
};
  

...然后使用敲除验证注册自定义绑定:

ko.validation.makeBindingHandlerValidatable('yourBindingName');