本文介绍了KnockoutJS中的最大值和数值验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I implement a max value validation and check if the observable's value is numerical, something like:

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

推荐答案

听起来像敲除验证插件之后的声音. https://github.com/Knockout-Contrib/Knockout-Validation

sounds like you might be after the knockout validation plugin. https://github.com/Knockout-Contrib/Knockout-Validation

运行下面的代码段.输入非数字或大于255的数字将导致显示消息.

run the snippet below. entering a non digit or something more than 255 will cause the message to display.

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>

这篇关于KnockoutJS中的最大值和数值验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 21:25