Problems with knockout-validation custom message template

RHarris picture RHarris · Jan 3, 2013 · Viewed 9k times · Source

I've not used Knockout Validation and I'm trying to get a feel for what can be done with it.

I'm trying to figure out if it is possible to display an icon rather than an error message to the right of an input tag when there is an error. And, if the user hovers over the icon, the error message is displayed.

Has anyone done this or have an idea of how to accomplish this?

Thanks.

EDIT: (more detailed example of what I'm trying to do)

Say I have the following in my view model:

var firstName = ko.observable().extend({required: true});

My HTML:

<input data-bind="value: firstName" />

My understanding is that if the first name textbox were left blank, then (by default) some text would be displayed to the right of the textbox stating that this field is required.

What I'm trying to understand is how to change the default behavior of displaying error text on the right to displaying an icon on the right which, when hovered over, will popup the error message.

So, a start would be something like:

<div data-bind="validationOptions: {messageTemplate: 'myCustomTemplate'}">    
    <input data-bind="value: firstName" />
    <input data-bind="value: lastName" /> //also required
</div>
<div id='myCustomTemplate'>
    //This icon should only display when there is an error
    <span class="ui-icon ui-icon-alert" style="display: inline-block"/>

    //css/javascript would display this when user hovers over the above icon
    <span data-bind="validationMessage: field"  />  
</div>

I have no clue if I'm using the messageTemplate feature correctly. I also wouldn't know what to bind the text to in the customTemplate in order to display the correct error message for each error. IOW, firstname and lastname could have custom error messages. If they are both using the same template, how does the template accomodate the custom error message?

I hope that makes sense.

Answer

delixfe picture delixfe · Jan 25, 2013

It is possible to show an icon and to display the error message on hovering.

In one project we are doing something similar. We show a badge with a error number, but we use decorateElement to highlight the fields and errorsAsTitleOnModified to show the errors when hovering over the input.

To create a error messageTemplate you should wrap your template in a script tag. It works like templates of the ko template binding.

Inside the template you can access the validated observable by referring to 'field'. The error message is stored in the property 'error' of your observable.

<script type="text/html" id="myCustomTemplate">
    <span data-bind="if: field.isModified() && !field.isValid(), 
                     attr: { title: field.error }">X</span>
</script>

I have created a fiddle to show this in action: http://jsfiddle.net/nuDJ3/180/