如何使用ko.validation.group函数 [英] How to use ko.validation.group function

查看:176
本文介绍了如何使用ko.validation.group函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用knockout.validation插件。我创建了一个exampleViewModel:

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

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

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.

我的问题是,如果我想创建一个只有3个属性(P1,P2,P3)的验证组,我将如何做到这一点?

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 ?

推荐答案

这对我来说效果很好。而不是在这个上进行分组,而是创建一个包含要验证的属性的代理对象。

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

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

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

这篇关于如何使用ko.validation.group函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆