0
votes

I'm trying to manually set an error on a computed observable using Knockout Validation but the validation message isn't displaying. I need to be able to set the error after apply bindings has been called and the group set.

var viewModel = {
    computedTest: ko.computed(function(){
        return 'Test'
    })
};
viewModel.errors = ko.validation.group(viewModel);

ko.applyBindings(viewModel);
viewModel.computedTest.extend({ validatable: true });
viewModel.computedTest.setError('oops');

viewModel.errors.showAllMessages(true);

Using this example a validationMessage doesn't get displayed for the computedTest observable.

I believe the reason is because the validation group hasn't doesn't know that computedTest is now extended. But I'm not sure how to refresh the group so that the error message is displayed.

Here's a better example: https://jsfiddle.net/onbyc67h/.

As you can see if you set the .extend({ validatable: true }) before applyBindings is run a message is displayed, but if you do it after one isn't.

Thanks

1
I'm trying to do it so I can map a collection of server validation errors on form submission. Everything is working fine except for this example where a computed observable is used instead of a regular one - Rich
Is there some reason you can't extend the computed initially? - Roy J

1 Answers

0
votes

What is going on is completely logical: when you apply bindings, the different bound properties are subscribed to changes of existing observables. So, if you create a new observable after binding, there is no way for ko to discover and subscribe to it. Take into account that what the validation extenders do is creating new observables, which can be subscribed. But, if you create them after binding, as explained, they can not be subscribed by the binders.

The only thing that you could do would be to unbind and rebind, but this is not advisable at all.