I have a KnockoutJS viewmodel that acts as a "master" viewmodel for several modular viewmodels. These modular vm's utilize knockout validated properties for their own form validations. I would like to make these viewmodels validatedObservable
in the master viewmodel, so I can simply check each if isValid
is true:
function MasterViewModel() {
var self = this;
self.addUserViewModel = ko.validatedObservable(new AddUserViewModel());
}
function AddUserViewModel() {
var self = this;
self.username = ko.observable().extend({ required: true });
self.addUser = = function () {
if(self.isValid()) {
// Perform add user logic here
}
}.bind(self);
}
However, the isValid
method does not exist for the child viewmodel when I attempt to call it. Is there an issue with adding a validatedObservable
property that is a function?
The isValid
is added by the function validatedObservable
and will therefore only be available inside the MasterViewModel
.
You could use ko.validation.group
when you want to check if the model is valid inside the model itself:
function AddUserViewModel() {
var self = this;
self.username = ko.observable().extend({ required: true });
var errors = ko.validation.group(self, { deep: true });
self.addUser = = function () {
if (!errors().length) {
// Perform add user logic here
}
};
}