Binding validation success/error message to errors array

778 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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.