I have two viewmodels, one is created with validation.group
and the other as validatedObservabel
. The method errors.showAllMessages()
fails for the second view model. Why?
function VM1 {
this.errors = ko.validation.group(this);
email:ko.observable().extend({required:true})
}
var vm1 = new VM1();
if (!vm1.isValid()) {
vm1.errors.showAllMessages(); //works fine
}
function VM2 {
this.errors = ko.validatedObservable(this);
email:ko.observable().extend({required:true})
}
var vm2 = new VM2();
if (!vm2.isValid()) {
vm2.errors.showAllMessages(); //fails
}
A validatedObservable is a wrapper on validation.group, which offers a few more features and functionality. It achieves this by internally creating a validation.group. In order to access validation.group methods (such as showAllMessages) you need to explicitly access the internal validation.group object via the 'errors' property on the validatedObservable.
i.e.
function VM2 {
this.errors = ko.validatedObservable(this);
email:ko.observable().extend({required:true})
}
var vm2 = new VM2();
if (!vm2.isValid()) {
vm2.errors.showAllMessages(); //fails
vm2.errors.errors.showAllMessages(); // Works!
}
Clearly it looks a bit weird to have errors.errors, but that is just because you named the validatedObservable 'errors'. The syntax looks nicer if you call it something like 'validationModel'
e.g.
function VM2 {
this.validationModel= ko.validatedObservable(this);
email:ko.observable().extend({required:true})
}
var vm2 = new VM2();
if (!vm2.isValid()) {
vm2.validationModel.errors.showAllMessages(); // Works!
}