如何使用ko.validation。组功能

时间:2023-01-15 11:13:45

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.

在上面的视图模型中,我为当前对象创建了一个名为errors的验证组。现在,如果任何验证规则在4的任何一个属性上失败,那么这个错误属性包含一个错误消息。

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 ?

我的问题是,如果我想在4个属性中创建一个只有3个属性(P1, P2, P3)的验证组,我该怎么做呢?

2 个解决方案

#1


53  

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.

如果您这样做,请考虑使用validatedObservable而不是group。您不仅可以得到错误,还可以使用isValid属性集体检查所有属性是否有效。

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

#2


11  

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

#1


53  

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.

如果您这样做,请考虑使用validatedObservable而不是group。您不仅可以得到错误,还可以使用isValid属性集体检查所有属性是否有效。

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

#2


11  

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