使用利用输入掩码的 Knockout 自定义绑定禁用 Knockout 验证

Using Knockout custom binding utilizing input mask disables Knockout Validation

我想将 Knockout 验证和 Knockout 自定义绑定与输入掩码一起使用 (http://robinherbots.github.io/jquery.inputmask/)。例子:钱输入框,我一开始就不想让用户可以输入任何字母字符,同时我也想限制最小和最大金额。

在我的 JSFiddle 中,您可以看到那些未自定义绑定的可观察对象具有工作验证,但其他的则没有。

http://jsfiddle.net/csabatoth/LkqTU/24841/

<div>
    <p>Title 1: <input data-bind='value: title1' /></p> 
    <p>Amount 1: <input data-bind='value: amount1' /></p> 
    <p>Title 2: <input data-bind='inputmask: { value: title2, mask: "*****" }' /></p> 
    <p>Amount 2: <input data-bind='inputmask: { value: amount2, mask: "money" }' /></p>
</div>

ko.bindingHandlers.inputmask =
{
    init: function (element, valueAccessor, allBindingsAccessor) {
        var mask = valueAccessor();
        var observable = mask.value;

        if (ko.isObservable(observable)) {
            $(element).on('focusout change', function () {
                if ($(element).inputmask('isComplete')) {
                    observable($(element).val());
                } else {
                    observable(null);
                }
            });
        }

        if (mask.mask === "money") {
            $(element).inputmask('decimal',
                                 {
                                     'alias': 'numeric',
                                     'groupSeparator': ',',
                                     'autoGroup': true,
                                     'digits': 2,
                                     'radixPoint': ".",
                                     'digitsOptional': false,
                                     'allowMinus': false,
                                     'prefix': '$ ',
                                     'placeholder': '0'
                                 }
                                );
        } else {
            if (mask.regex)
                $(element).inputmask('Regex', { regex: mask.mask });
            else
                $(element).inputmask(mask.mask);
        }
    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var mask = valueAccessor();
        var observable = mask.value;

        if (ko.isObservable(observable)) {
            var valuetoWrite = observable();
            $(element).val(valuetoWrite);
        }
    }
};

var ViewModel = function() {
    var self = this;

    self.convertMoneyToFloat = function (moneyVal) {
        var value = parseFloat(moneyVal.replace(/[^\.\d]/g, ""));
        return value;
    }

    self.title1 = ko.observable("T1").extend({ maxLength: 5 });
    self.title1.subscribe(function (newValue) {
        console.log("AJAX write T1 " + newValue);
    });
    self.amount1 = ko.observable(110.0).extend({ number: true, min: 10.0, max: 10000.0 });
    self.amount1.subscribe(function (newValue) {
        console.log("AJAX write A1 " + newValue);
    });
    self.title2 = ko.observable("T2").extend({ maxLength: 5 });
    self.title2.subscribe(function (newValue) {
        console.log("AJAX write T2 " + newValue);
    });
    self.amount2 = ko.observable(110.0).extend({ number: true, min: 10.0, max: 10000.0 });
    self.amount2.subscribe(function (newValue) {
        console.log("AJAX write A1 " + self.convertMoneyToFloat(newValue));
    });
};

ko.applyBindings(new ViewModel());

正如您在此 fiddle 中看到的那样,验证工作正常:http://jsfiddle.net/L5ndbnba/2/

问题是屏蔽字段的消息不会自动显示,因此您应该通过添加 <span data-bind="validationMessage: amount2"></span>.

显式显示验证消息

现在,由于掩码值存储在 amount2 中,您需要将验证规则应用于可计算的数字以使其正常工作:

self.amount2 = ko.observable(110.0);

self.amount2Numeric = ko.computed(function() {
    return self.convertMoneyToFloat(self.amount2());
});

self.amount2Numeric.extend({ number: true, min: 10.0, max: 10000.0 });

这是完整的工作 fiddle:http://jsfiddle.net/L5ndbnba/3/