Validation 如何限制敲除js中的输入字段数字
我有一个输入字段,我只想对数值进行限制。我如何在淘汰赛中做到这一点 这是我的领域Validation 如何限制敲除js中的输入字段数字,validation,knockout.js,Validation,Knockout.js,我有一个输入字段,我只想对数值进行限制。我如何在淘汰赛中做到这一点 这是我的领域 <input data-bind="value: nsc" /> 我猜这个问题已经回答了。 您可能需要创建只接受允许字符的自定义绑定 此链接中的帖子答案将帮助您:您可以在视图模型中编写函数 ko.extenders.numeric = function(target, precision) { //create a writable computed observable to intercept
<input data-bind="value: nsc" />
我猜这个问题已经回答了。 您可能需要创建只接受允许字符的自定义绑定
此链接中的帖子答案将帮助您:您可以在视图模型中编写函数
ko.extenders.numeric = function(target, precision) {
//create a writable computed observable to intercept writes to our observable
var result = ko.pureComputed({
read: target, //always return the original observables value
write: function(newValue) {
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
//only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({ notify: 'always' });
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
})
检查此链接如何使用:使用淘汰验证@Seminda给出的答案比您链接的问题中的答案要好得多。这是迄今为止最好的方法。(也比发布的@Raghavendra-N链接中公认的答案要好)。这主要是因为两个原因:扩展器比自定义绑定灵活得多,并且它促进了更好的代码分离。我的意思是,只在JavaScript中设置数字限制更有意义,因为它表示域逻辑,而不是HTML中与表示有关的内容。嗨,汉斯,你能回答这个问题吗@Seminda给出的答案比你链接的问题中的答案要好得多。定制绑定并不是实现这一点的理想解决方案,扩展器更灵活,还提供了更好的代码分离(HTML不应该支配域逻辑,JavaScript应该)。