角度 2 组验证 [英] angular 2 group validation

查看:21
本文介绍了角度 2 组验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定简单的注册表:

this.registerForm = this.formBuilder.group({
    email:['', Validators.compose([
    Validators.required,
    Validators.pattern('.+@.+\..+'),
    ]), this.validators.isTaken],
    matchingPassword: this.formBuilder.group({
    password: ['', Validators.compose([
            Validators.required,
            Validators.maxLength(30),
            Validators.minLength(8)
        ])],
    passwordConfirmation: ['', Validators.compose([
            Validators.required,
        ])]
    }, {validator: this.validators.match})
})

我正在尝试验证密码确认匹配,因此我将匹配验证器应用于表单组.但是现在我面临的情况是字段本身显示为有效(带有绿色边框,因为它的所有验证器都通过)但组验证器不是,我需要它们显示为红色.

I'm trying to validate password confirmation match so I'm applying match validator to form group. But now I'm facing a situation when the field itself displayed as valid (with green border because all its validators are passing) but group validator are not and I need them to be shown as red.

那么我应该手动将 ng-valid 更改为 ng-invalid 还是有一些技巧可以更好地解决这个问题?

So should I change ng-valid to ng-invalid manually or there are some trick to fix this in better way?

推荐答案

我刚刚在这里回答了这个问题 [1].

I have just answered this question over here [1].

基本上 angular 不会假设您要使组的所有字段无效,因为该组无效.您可以在模板本身中补充该信息.

Basically angular does not assume you want to invalidate all fields of a group because the group is invalid. You can complement that information in the template itself.

我没有您的模板,但我或多或少可以假设您可以通过以下方式将控件更改为无效:

I do not have your template, but I can more or less assume you can change your controls to be invalidated in the following way:

<input [ngClass]="{'ng-invalid': registerForm.get('matchingPassword').hasError('nomatch')}" type="text" placeholder="Password" formControlName="password">

<input [ngClass]="{'ng-invalid': registerForm.get('matchingPassword').hasError('nomatch')}" type="text" placeholder="Confirm password" formControlName="passwordConfirmation">

您可能需要调整自定义验证器返回的占位符和错误名称匹配.

You will likely have to adjust the placeholders and error name returned by the custom validator match.

[1] 嵌套 FormGroup 的 FormControl 是 ng-valid 尽管 FromGroup 是 ng-invalid

这篇关于角度 2 组验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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