KnockoutJs BindingHandlers取消验证

时间:2015-05-19 14:17:54

标签: javascript knockout.js bindinghandlers

我正在使用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',则验证工作正常。

任何线索?

0 个答案:

没有答案