knockout-validation: render html tag in message

1k views Asked by At

In the MVC + knockout project client wants to have a link in validation message.

JS file:

ko.validation.rules['standardCharsValidation'] = {
validator: function (val, params) {
    return /^$|^[a-zA-Z0-9 \&,.\\\/;:\[\]\-\(\)\_\!\'\`]+$/.test(val);
},
message: 'Error: Invalid text entered, please see <a class=\'CssLinkClass\' target=\'_blank\' href=\'' + Controllers.HomeHelp + '\'>Help</a>'
};

And in view:

     <input type="text" id="Postcode" class="input-xsmall" name="Postcode" id="Postcode" data-bind="value: Postcode, valueUpdate: 'afterkeydown'"/>
            <label class="error" style="text-align: left;" data-bind="validationMessage: Postcode"></label>

The results are as follow

Error: Invalid text entered, please see <a class='CssLinkClass' target='_blank' href='/Home/Help'>Help</a>

Is there any way to make it render that element properly?

1

There are 1 answers

0
Derpy On BEST ANSWER

Using a custom validation message template can give you the desired result. This particular implementation injects a custom message in the middle "Error: <custom message>, please see <help link>"

http://jsfiddle.net/vmmbhwes/1/

<script type="text/html" id="helpLinkTemplate">
    <span data-bind="if: field.isModified() && !field.isValid()">
        Error: <span data-bind='validationMessage: field'></span>, please see&nbsp;
        <a class='' target=\'_blank\' href="http://stackoverflow.com">Help</a>
    </span>
</script>

By selectively wrapping your input fields with a custom validation template, you can apply your custom templates as needed

<div data-bind="validationOptions: {messageTemplate: 'helpLinkTemplate'}">
    UserName (custom template):<br/>
    <input data-bind="value: name" />
</div>
Number (standard template):<br/>
<input data-bind="value: number" />