Angular 中自定义验证器的问题

Problems with the custom validator in Angular

我知道这个问题已经在许多其他帖子中提出过,但在所有建议的解决方案中我找不到适合我的解决方案。

我正在尝试创建一个验证器来检查输入的确认密码是否与密码相同。

这是我的构建表单代码:

    this.form = new FormGroup({
      name: new FormControl('', [Validators.required]),
      surname : new FormControl('', [Validators.required]),
      username: new FormControl('', [Validators.required, Validators.email]),
      tempUsername: new FormControl('', [Validators.required, Validators.email]),
      password: new FormControl('', [Validators.required, Validators.minLength(8), Validators.maxLength(16)]),
      passwordTemp: new FormControl('', [Validators.required]),
    }, { validator: this.matchingPasswords }
    );
  }

这是我的验证器方法:

  public matchingPasswords(c: AbstractControl): ValidationErrors | null {
    const password = c.get(['passwords']);
    const confirmPassword = c.get(['passwordTemp']);

    if (password.value !== confirmPassword.value) {
      return { mismatchedPasswords: true };
    }
    return null;
  }

在构建表单的第 8 行中,我收到以下错误:

TS2345: Argument of type '{ validator: (c: AbstractControl) => ValidationErrors; }' is not assignable to parameter of type 'ValidatorFn | ValidatorFn[] | AbstractControlOptions'.   Object literal may only specify known properties, and 'validator' does not exist in type 'ValidatorFn | ValidatorFn[] | AbstractControlOptions'.

有什么想法吗?

你应该使用 validators 而不是 validator:

this.form = new FormGroup({
 // fields
}, { validators: this.matchingPasswords });

也许将 matchingPasswords 移动到导出的实用程序函数也更好,但这只是个人代码偏好。

其他工作符号是:

this.form = new FormGroup({
 // fields
}, this.matchingPasswords);
this.form = new FormGroup({
 // fields
}, [this.matchingPasswords]);

使用验证器代替验证器

{ validators: this.matchingPasswords }

还有这个

public matchingPasswords: ValidatorFn = (c: AbstractControl): ValidationErrors | null => {
        const password = c.get('passwords');
        const confirmPassword = c.get('passwordTemp');

        if (password && confirmPassword && password.value !== confirmPassword.value) {
            return { mismatchedPasswords: true };
        }

        return null;
    };