I am having some trouble getting validation errors to display on a model driven form with Angular (v4.3.6).
In my model, I have the following:
this.registerForm = formBuilder.group({
'email':[null,Validators.compose([Validators.required, ValidateEmail])],
'firstName':[null, Validators.required],
'lastName':[null, Validators.required],
'passwordGroup': formBuilder.group({
'password':[null, Validators.compose([Validators.required,Validators.minLength(8)])],
'passwordConfirmation':[null, Validators.required],
},{validator: ValidatePasswordConfirmation})
});
The ValidatePasswordConfirmation custom validator referenced is as follows:
export function ValidatePasswordConfirmation(group: FormGroup) {
if(group.value.password !== group.value.passwordConfirmation){
return { 'no-match':true };
}
return null;
}
Lastly, in my template I have the following:
<md-form-field>
<input mdInput name="passwordConfirmation" placeholder="Confirm password" [formControl]="registerForm.controls['passwordGroup'].controls['passwordConfirmation']" [(ngModel)]="model.passwordConfirmation" type="password">
<md-error *ngIf="registerForm.controls['passwordGroup'].controls['passwordConfirmation'].hasError('required')">
Password confirmation is required
</md-error>
<md-error *ngIf="registerForm.controls['passwordGroup'].hasError('no-match')">
Passwords don't match
</md-error>
</md-form-field>
However, the md-error governed by the 'no-match' error never shows up. So, to debug this on the page I added the following:
no-match = {{registerForm.controls['passwordGroup'].hasError('no-match')}}
invalid = {{registerForm.controls['passwordGroup'].invalid}}
Unsurprisingly, the debug lines show true/false as you would expect. However, the 'md-error' is never displayed... except for when the 'required' error is shown. I have a feeling that the issue is due to the [formControl] referring to the passwordConfirmation FormControl, and so without that being invalid, the md-error is not shown. However, I would like this error to display when the outer FormGroup is invalid.
Any pointers on where I'm going wrong here would be really helpful!
Finally, I have tried a few other ways around this such as setting the error on the PasswordConfirmation FormControl, which works, but I would like to know why my current implementation is failing.