1

我正在使用 knockout.js 并添加一个 BindingHandlers 来将 observable 格式化为十进制。问题是,当我应用此绑定时,所需的验证消息没有出现。

这是代码

function formatWithComma(x, precision, seperator) {
        var options = {
            precision: precision || 2,
            seperator: seperator || ','
        }
        var formatted = parseFloat(x, 10).toFixed(options.precision);
        var regex = new RegExp(
                '^(\\d+)[^\\d](\\d{' + options.precision + '})$');
        formatted = formatted.replace(
            regex, '$1' + options.seperator + '$2');
        return formatted;
    }

    function reverseFormat(x, precision, seperator) {
        var options = {
            precision: precision || 2,
            seperator: seperator || ','
        }
        var regex = new RegExp(
            '^(\\d+)[^\\d](\\d+)$');
        var formatted = x.replace(regex, '$1.$2');
        return parseFloat(formatted);
    }

    ko.bindingHandlers.commaDecimalFormatter = {
            init: function (element, valueAccessor) {
                var observable = valueAccessor();

                var interceptor = ko.computed({
                    read: function () {
                        if (!observable())
                            return 0;
                        else
                            return formatWithComma(observable());
                    },
                    write: function (newValue) {
                        observable(reverseFormat(newValue));
                    }
                });

                if (element.tagName == 'INPUT')
                    ko.applyBindingsToNode(element, {
                        value: interceptor
                    });
                else
                    ko.applyBindingsToNode(element, {
                        text: interceptor
                    });
            },
            update: function (element, valueAccessor) {

                var observable = valueAccessor();

                var interceptor = ko.computed({
                    read: function () {
                        if (!observable())
                            return 0;
                        else
                            return formatWithComma(observable());
                    },
                    write: function (newValue) {
                        observable(reverseFormat(newValue));
                    }
                });          
            }
        }
        ko.validation.makeBindingHandlerValidatable('commaDecimalFormatter'); 

——可观察的

self.Number = ko.observable(0).extend({
    required: {
        params: true,
        message: "Requerido"
    }
});

--- 和输入

<input id="txtGroam" data-bind="commaDecimalFormatter: Model().Number, valueUpdate: 'keyup'" />
<p class="text-danger-alt" data-bind="validationMessage: Model().Number"></p>

如果我使用 'value' 而不是 'commaDecimalFormatter',则验证工作完美。

有什么线索吗?

4

0 回答 0