KnockoutJS中的最大值和数值验证

时间:2017-03-21 08:41:10

标签: knockout.js knockout-validation

如何实现最大值验证并检查可观察值是否为数字,如:

self.MyInteger = ko.observable().extend({ numeric: 2 })
                               .extend({ maxValue: { params: 255, message: "MyInteger cannot be greater than 255" } });

2 个答案:

答案 0 :(得分:1)

听起来你可能是在淘汰赛验证插件之后。 per the docs

运行下面的代码段。输入非数字或超过255的内容将导致显示消息。

function model() {
  var self = this;
  this.myObj = ko.observable().extend({ digit: true }).extend({ max: 255});
  }
  
  var mymodel = new model();

$(document).ready(function() {
  ko.validation.init();
  ko.applyBindings(mymodel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>

enter a digit less than or equal to  255 <input type="text" data-bind="textInput: myObj">

<p>
  Enter something other than a digit or over 255 will cause an error.
</p>

答案 1 :(得分:0)

要在验证可观察对象后显示错误消息,您可以执行以下操作:

var ViewModel = function() {
  var self = this;
  self.myInteger = ko.observable().extend({ validation: "Please pass numerical value that is less than 255" });
}

ko.extenders.validation = function (target, overrideMessage) {

  target.hasError = ko.observable();
  target.validationMessage = ko.observable();

  function validate(newValue) {
    // write your validation here
    // check if it is numerical
    // check if it is less than the max value
    var passTheValidation = true;
    target.hasError(!passTheValidation);
    target.validationMessage(passTheValidation ? "" : overrideMessage || "This failed the validation");
  }

  //initial validation
  validate(target());

  //validate whenever the value changes
  target.subscribe(validate);

  //return the original observable
  return target;
}

然后显示如下错误消息

<div>
  <input data-bind='value: myInteger, valueUpdate: "afterkeydown"' />
  <span data-bind='visible: myInteger.hasError, text: myInteger.validationMessage'> </span>
</div>

网站上有关此扩展程序http://knockoutjs.com/documentation/extenders.html

的参考资料