Reputation: 1681
I'm using the knockout validation plugin and grouping to generate an errors array.
self.errors = ko.validation.group(self);
I also have a messagebox object
function messagebox(status, message) {
var self = this;
self.status = ko.observable(status);
self.message = ko.observable(message);
}
that I instantiate in the viewmodel and it renders successfully in the view:
self.msgbox = new messagebox("information", "Enter some integers");
The messagebox updates at various states to provide information or alerts. I want it to update when validation fails or succeeds.
e.g.
if (self.errors().length = 0) {
self.msgbox.status("success");
self.msgbox.message("Validation successful");
} else {
self.msgbox.status("error");
self.msgbox.message("+ or - integers required");
}
Can anybody suggest how to get the above to work? Do I need a computed observable?
Upvotes: 3
Views: 769
Reputation: 139798
You don't necessary to create a computed if you use the validation plugin the setting grouping: { observable: true }
(which is the default) then the ko.validation.group
will return a ko.computed
what you can just subscribe
on:
self.errors.subscribe(function () {
if (self.errors().length == 0) {
self.msgbox.status("success");
self.msgbox.message("Validation successful");
} else {
self.msgbox.status("error");
self.msgbox.message("+ or - integers required");
}
});
Demo JSFiddle.
Upvotes: 3