我不明白为什么会出现这个错误。每次输入时,都会显示以下错误:
错误:期望验证器返回Promise或Observable。
我正在尝试使用的代码:
验证器:
export function passwordMatchValidator(passwordKey: string, passwordConfirmationKey: string, group: FormGroup): any {
if (group) {
if (group.get(passwordKey).value !== group.get(passwordConfirmationKey).value) {
return { 'passwordMismatch': true };
}
}
return null
}
FormGroup代码:
this.formGroup.setValidators(passwordMatchValidator("password", "confirmPassword", this.formGroup));
this.formGroup.updateValueAndValidity();
HTML:
<mat-error *ngIf="formGroup.controls['confirmPassword'].errors?.passwordMismatch"></mat-error>
我创建了一个简单的Stacklitz示例。
表单组
this.formGroup = new FormGroup(
{
password: new FormControl(),
passwordConfirm: new FormControl()
},
{ validators: passwordMatchValidator }
);
验证器
export function passwordMatchValidator(g: FormGroup) {
return g.get("password").value === g.get("passwordConfirm").value
? null
: { mismatch: true };
}
HTML
<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
Password: <input formControlName="password" placeholder="Password"><br>
Confirm Password: <input formControlName="passwordConfirm" placeholder="Confirm Password"><br>
<span *ngIf="formGroup.errors && formGroup.errors.mismatch"
[style.color]="'red'">Password Mismatch</span><br>
<button type="submit">Submit</button>
</form>
通过导入ValidationErrors来修复它,如下所示:
export function passwordMatchValidator(passwordKey: string, passwordConfirmationKey: string): ValidatorFn {
return (group: FormGroup): ValidationErrors => {
const control = group.controls[passwordKey];
const matchingControl = group.controls[passwordConfirmationKey];
if (matchingControl.errors && !matchingControl.errors.passwordMismatch) {
// return if another validator has already found an error on the matchingControl
return;
}
// set error on matchingControl if validation fails
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ 'passwordMismatch': true});
} else {
matchingControl.setErrors(null);
}
return;
}
}