1
votes

I have a simple JSFiddle example http://jsfiddle.net/b625zeL5/6/

<script>
ko.validation.init({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: false,
    parseInputAttributes: true,
    messageTemplate: 'errorTemplate',
    decorateInputElement: true,
    errorElementClass: 'error'
}, true);

var ViewModel = function(){
    this.email = ko.observable("")
        .extend({ required: true })
        .extend({ email: true });

    this.password = ko.observable("")
        .extend({ required: true });
};

var viewModel = new ViewModel();

viewModel.errors = ko.validation.group(viewModel);

ko.applyBindings(viewModel);
</script>
<form>
    <span data-bind="validationMessage: email"></span>
    <input type="text" id="email" data-bind="value: email, validationElement: email, valueUpdate:'keyup'" /> <br/>
    <span data-bind="validationMessage: password"></span>
    <input type="text" id="password" data-bind="value: password, validationElement: password, valueUpdate:'keyup'"/>
</form>

<script type="text/html" id="errorTemplate">
    Error: <span data-bind="validationMessage: field">X</span>
</script>

As you can see - I disabled insertMessages because I need error messages to show before input field. Thus I added span with "data-bind="validationMessage: email"" before each text input.

I defined in validation config messageTemplate: 'errorTemplate' but error messages still plain text. How can I get messageTemplate to work?

1
Aside of your q I just wanted to say: after a year of working with KO i threw this away I and got to AnguarJS and React. Now you have also Meteor avaliabile. Coding in AngularJS is about 3-4 times faster than KO. I hope you will think about my words and try to swap from KO to Angular. RegardsPaweł Smołka

1 Answers

0
votes

Because you turned off insertMessages, knockout validation won't use your error message template and it will use what you inserted above each field.

You have two options:

  1. For each observable that has a validation, add a custom error message.

Example 1:

 this.password = ko.observable("")
        .extend({ required: {
            params: true,
            message: "Error: This is required"
        }
    });
  1. Change your error template to something like this:

Example 2:

<script type="text/html" id="errorTemplate">
    Error: <span data-bind="validationMessage: error_field"></span>
</script>

.. and inside the form, you can call the template like:

<form>
    <!-- ko template: { name: 'errorTemplate', data: { error_field: email } }-->
    <!-- /ko -->
    <input type="text" id="email" data-bind="value: email, validationElement: email, valueUpdate:'keyup'" /> <br/>
    ...
    ...

see jsfiddle here with example 2 in action : http://jsfiddle.net/mhgv48e8/

Hope it helps :)