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

查看:61
本文介绍了角度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].

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

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">

您可能必须调整自定义验证程序 match 返回的占位符和错误名称.

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

[1] 查看全文

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