Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

javascript - How to use ko.validation.group function

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...