Search code examples
knockout.jsknockout-validation

how to show one validation icon for radiobuttons group


I'm using knockoutjs and knockout validation plugin.

I would like to show one validation icon for the radio group, after 'Question 1' title. How can I do this?

<label>Question 1:</label>
<div>
    <!-- ko foreach: answers -->
    <div>
        <input type="radio" data-bind="attr: { value: id, id: id, name: 'answers' }, checked: $parent.selectedValue" />
        <label data-bind="text: text, attr: { for: id }"></label>
    </div>
    <!-- /ko -->
</div>

There is an jsfiddle example

Also the second question - why validation icons are displaying always in this example?

Thanks!


Solution

  • You can put a validation message on another element by using the validationMessage binding handler:

    This shows the validation message:

    <label>Question 1:
        <span data-bind="validationMessage: selectedValue"></span>
    

    This example shows a custom message template:

    <label>Question 1:
            <input style="display:none" 
                data-bind="value:selectedValue, 
                           validationOptions: {messageTemplate: 'icon'}" />
    </label>
    

    Or more simply, if you want to use the default messageTemplate:

    <label>Question 1:
            <input style="display:none" data-bind="value:selectedValue" />
    </label>
    

    As for the second question, the messageTemplate is processed whether the field is valid or not. This allows you to show a validation message (say a green chackmark) while the field is valid, and show a validation error once it becomes invalid.

    You can use the if binding handler in conjunction with the field variable to control when the message is visible.

    <script type="text/html" id="icon">
        <span data-bind="if: field.isModified() && !field.isValid()">X<span>
    </script>