【发布时间】:2021-02-17 14:28:33
【问题描述】:
密码和确认不匹配,如果表单无效,按钮将被禁用,但<mat-error> 中的消息仍不显示
模板文件
<mat-form-field class="full-width" appearance="outline">
<mat-label>Password</mat-label>
<input type="password" formControlName="password" matInput required />
<mat-error *ngIf="AuthForm.get('password').errors">Valid Password required</mat-error>
</mat-form-field>
<mat-form-field class="full-width" appearance="outline">
<mat-label>Password Confirmation</mat-label>
<input type="password" formControlName="passwordConfirmation" matInput required />
<mat-error *ngIf="AuthForm.get('password').touched && AuthForm.get('passwordConfirmation').touched && AuthForm.errors"> Passwords dont match!</mat-error>
</mat-form-field>
<button [disabled]="AuthForm.invalid" mat-flat-button color="primary">Register</button>
外部类验证器
import { Injectable } from '@angular/core'
import { Validator, FormGroup } from '@angular/forms'
@Injectable({ providedIn: 'root' })
export class MatchPassword implements Validator {
validate(formGroup: FormGroup) {
const passwordControl= formGroup.get('password');
const passwordConfirmControl= formGroup.get('passwordConfirmation')
if (passwordControl.value != passwordConfirmControl.value) {
return { passwordsDontMatch: true }
}
else {
return null;
}
}
}
组件类
export class AdminComponent implements OnInit {
AuthForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email, Validators.minLength(10),
Validators.maxLength(25)]),
password: new FormControl('', [Validators.required, Validators.minLength(4),
Validators.maxLength(20)]),
passwordConfirmation: new FormControl('', [Validators.required,
Validators.minLength(4),
Validators.maxLength(20),
]
)
}, {validators : [this.MatchPassword.validate]})
constructor( private MatchPassword: MatchPassword) { }
【问题讨论】:
标签: angular validation angular-material angular-reactive-forms