0

我在 JSFiddle 中设置了一个示例, http://jsfiddle.net/4stu2jg3/63/

如果您在第一个文本框中添加非数字数字并单击按钮,则会显示所需的消息。我会假设这应该显示数字消息,因为有一个值?

在第二个文本框中,如果您删除字符串并单击按钮,则会显示数字消息。我希望这能显示所需的信息?

如果您注释掉自定义模板,一切都会按我的预期工作。我不确定我做错了什么?

<div id="test">
    <div><input data-bind="value: first" /></div>
    <div><input data-bind="value: last" /></div>

    <input type="button" value="Validate" />
</div>

<script type="text/html" id="qmsKoValidationTemplate">
    <span class="qms-val-panel" data-bind="visible: field.isModified() && !field.isValid(), text: field.error"></span>
</script>

ko.validation.init({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: false,
    messageTemplate: "qmsKoValidationTemplate"
});

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

    self.first = ko.observable()
        .extend({required: { message: 'Required' } })
        .extend({number: { message: 'Number' } });

    self.last = ko.observable('Del')
        .extend({required: { message: 'Required' } })
        .extend({number: { message: 'Number' } });
}

var s = new t();

ko.applyBindings(s, document.getElementById('test'));

$('input[type="button"]').click(function() {    
    //console.log(s.first(), s.last());
    //console.log(ko.validatedObservable(s).isValid())
    ko.validatedObservable(s).isValid()
});
4

1 回答 1

1

Using a bit of debug, ko.isObservable(field.error) returns false which would explain the "not changing" aspect of the issue.

In looking closer, the custom binding validationMessage is used in the default template. Replacing the text binding with this custom binding appears to provide the desired behavior.

<span class="qms-val-panel" data-bind="visible: field.isModified() && !field.isValid(), validationMessage: field">        
</span>

Modified fiddle

于 2014-11-11T22:01:22.043 回答