问题
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