knockout-validation - Custom Template Validation Messages are not changing

1.9k views Asked by At

I have set up an example in JSFiddle, http://jsfiddle.net/4stu2jg3/63/

In the first textbox if you add a non-numeric number and click the button is will show the required message. I would assume this should be showing the number message since there is a value?

In the second textbox if you delete the string and click the button is will show the number message. I would expect this to show the required message?

If you comment out the custom template everything works as I would expect it to. I am not sure what I am doing wrong?

<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()
});
1

There are 1 answers

0
Origineil On BEST ANSWER

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