angular 2 group validation

ぃ、小莉子 提交于 2020-01-04 05:29:07

问题


Given simple registration form:

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.

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

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

[1] FormControl`s of nested FormGroup are ng-valid although FromGroup is ng-invalid



来源:https://stackoverflow.com/questions/38938050/angular-2-group-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!