33

I am trying to use knockout.validation plugin. I created an exampleViewModel :

function exampleViewModel() {
   this.P1 = ko.observable().extend({ required : true });
   this.P2 = ko.observable().extend({ required : true });
   this.P3 = ko.observable().extend({ required : true });
   this.P4 = ko.observable().extend({ required : true });

   this.errors = ko.validation.group(this);
}    

In the above view model i created a validation group named errors for the current object. Now if any validation rule fails on any 1 property out of 4 than this errors property contains an error message.

My question is , if i want to create a validation group of only 3 properties (P1, P2, P3) out of 4 than how can i do this ?

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Tom Rider
  • 2,747
  • 7
  • 42
  • 65

2 Answers2

58

This worked well for me. Rather than grouping on this, create a proxy object that holds the properties you want validated.

this.errors = ko.validation.group({
    P1: this.P1,
    P2: this.P2,
    P3: this.P3
});

If you do this, consider using validatedObservable instead of group. Not only do you get the errors, but you can collectively check if all the properties are valid using the isValid property.

this.validationModel = ko.validatedObservable({
    P1: this.P1,
    P2: this.P2,
    P3: this.P3
});

// is the validationModel valid?
this.validationModel.isValid();
// what are the error messages?
this.validationModel.errors();
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • Used this approach to debug Durandal Observable Plugin validation issue. `this.errors = ko.validation.group({ P1: observable(this, 'P1') });` I believe it should have detected the getter/setters and reacted accordingly, but this at least proved the validation works. – MrYellow Mar 18 '15 at 02:42
14

As described in the documentation the right way to validate only specific observables is:

this.errors = ko.validation.group([this.P1, this.P2, this.P3]);
eduardobursa
  • 204
  • 2
  • 11
  • 6
    From the documentation: >"Notice also that the first parameter does not need to be an array. If you have only a single object, you can pass it in as a bare object, without wrapping it in an array." – Vinney Kelly Nov 12 '13 at 20:32
  • 1
    tks for the documentation link! – Alex Apr 13 '16 at 18:36