尝试创建密码确认验证器时出错期望的验证器返回Promise或Observable

问题描述

我不知道为什么会出现此错误。每次输入时,都会显示以下错误:

错误:预期的验证程序返回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>

解决方法

我创建了一个简单的Stackblitz示例。

formGroup

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;
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...