Reputation: 5355
How to create a knockout validation group that validates only some of the properties of the model, not all of them.
For instance, I have model with a bunch of observables and I want two different validation groups. As a simple example below I want to be able to validate first two properties seperatly from second two properties.
This scenario is necessary to validate Wizard steps where all observables from each wizard step sit in one model.
var mymodel = function() {
var self = this;
self.companyName = ko.observable().extend({ required: true });
self.contactPerson = ko.observable().extend({ required: true });
self.companyName2= ko.observable().extend({ required: true });
self.contactPerson2 = ko.observable().extend({ required: true });
// self.validationGroup1
// self.validationGroup2
};
Upvotes: 0
Views: 730
Reputation: 3685
If you are constructing a wizard you should use a viewmodel for each step. Knockout-validation provides the validatedObservable to know if all your viewmodel is valid and also in knockout you can have parent viewmodels so you could write something like this.
var mymodel = function() {
var self = this;
self.step1 = ko.validatedObservable({
companyName: ko.observable().extend({ required: true });
contactPerson: ko.observable().extend({ required: true });
});
self.step2 = ko.validatedObservable({
companyName: ko.observable().extend({ required: true });
contactPerson: ko.observable().extend({ required: true });
});
};
To know if any of the steps is valid just use
self.step1.isValid();
And to access any of the properties you can use
self.step1().companyName() ==> value
Upvotes: 1