如何在knockout js中限制输入字段数字

时间:2014-08-28 05:22:50

标签: validation knockout.js

我有一个输入字段,我想仅限制数字值。我怎么能在淘汰赛中做到这一点

这是我的字段

 <input data-bind="value: nsc" />

2 个答案:

答案 0 :(得分:4)

您可以在视图模型中编写函数。

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;

};

点击此链接如何使用:Sample code

答案 1 :(得分:0)

猜猜这个问题已经回答了。 您可能需要创建仅接受允许字符的自定义绑定。

此链接中帖子的答案可以帮助您:make an input only-numeric type on knockout