Custom knockout binding to display error messages

907 views Asked by At

I am currently using virtual elements to display validation errors (there can be more than 1 per path).

<div data-bind="foreach: validationErrors">
    <!-- ko if: path == 'title' && type == 'validation' -->
    <div class="field-validation-error text-danger" data-bind="text: message"></div>
    <!-- /ko -->
</div>

An example error that will be consumed by this is:

{
   path: 'title',
   type: 'validation',
   message: 'Title is required'
}

How can I achieve the same thing using a custom binding? I can't seem to find an intelligible example close enough to what I'm doing to be of any use.

1

There are 1 answers

2
TSV On

Simple wrapped it to the component:

ko.components.register('errors', {
    viewModel: function(params) {
        this.validationErrors = params.errors;
    },
    template:
        '<div data-bind="foreach: validationErrors">\
         <!-- ko if: path == "title" && type == "validation" -->\
         <div class="field-validation-error text-danger" data-bind="text: message"></div>\
         <!-- /ko -->\
         </div>'
});

var model = {
  errorsFromModel: ko.observableArray([
    {path: 'title', type: 'validation', message: 'Title is required'}
  ])
};

ko.applyBindings(model);

setTimeout(function() { model.errorsFromModel.push({path: 'title', type: 'validation', message: 'Another error added after 1 sec'}) }, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<errors params="errors: errorsFromModel"></errors>