【问题标题】:Max value and numerical validation in KnockoutJSKnockoutJS 中的最大值和数值验证
【发布时间】:2017-08-12 19:38:40
【问题描述】:
如何实现最大值验证并检查 observable 的值是否为数字,例如:
self.MyInteger = ko.observable().extend({ numeric: 2 })
.extend({ maxValue: { params: 255, message: "MyInteger cannot be greater than 255" } });
【问题讨论】:
标签:
knockout.js
knockout-validation
【解决方案1】:
听起来您可能正在使用淘汰赛验证插件。 https://github.com/Knockout-Contrib/Knockout-Validation
运行下面的sn-p。输入非数字或超过 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>
【解决方案2】:
要在验证可观察对象后显示错误消息,您可以执行以下操作:
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