如何解决我在使用自定义验证程序语法时遇到的错误?

How do I resolve the error I am encountering using custom Validator syntax?

我正在尝试创建一个自定义验证器来比较两个应该匹配的密码,如果它们不匹配,则应禁用按钮,如果匹配则用户可以完成注册。

在搜索 Stack Overflow 并浏览其他站点后,我重写了自定义验证器以匹配之前提供的答案;但是,其中 none 似乎对我遇到的错误有任何影响。

进口

import { FormControl, Validators, FormGroup, ValidatorFn, AbstractControl } from "@angular/forms";
import { Component } from "@angular/core";
import { MatButton } from "@angular/material";

表格组

registerForm = new FormGroup({
    first: new FormControl(null, [
      Validators.required,
    ]),
    last: new FormControl(null, [
      Validators.required,
    ]),
    id: new FormControl(null, [
      Validators.required,
    ]),
    email: new FormControl(null, [
      Validators.required,
      Validators.email
    ]),
    newpass: new FormControl(null, [
      Validators.required,
      this.ageRangeValidator
    ]),
    confirmpass: new FormControl(null, [
      Validators.required,
      this.ageRangeValidator
    ]),
  }, {this.matchingPasswords} );

自定义验证器

matchingPasswords(c: AbstractControl): {[key: string]: any} {
    let password = c.get(['passwords']);
    let confirmPassword = c.get(['confirmpwd']);

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

当我尝试 运行 这段代码时,我 运行 出现了以下错误。

Argument of type '{ this: any; }' is not assignable to parameter of type 'ValidatorFn | ValidatorFn[] | AbstractControlOptions'. Object literal may only specify known properties, and 'this' does not exist in type 'ValidatorFn | ValidatorFn[] | AbstractControlOptions'.ts(2345)

这是一个学校高级项目。

看来问题出在对

的调用上
this.matchingPasswords

验证器必须是静态函数。所以不要使用 this 关键字。您可以将 matchingPasswords 定义为纯 javascript 函数,也可以将其定义为打字稿 class 中的静态函数(推荐方法)。然后在您的模块中包含 class 并将函数作为 ClassName.matchingPasswords;

传递

您 return 为 null 或 ValidatorError 而不仅仅是具有任何 属性 的对象。 更改 matchingPasswords 方法的 属性 类型 return:

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

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

对于 html 参考,我会检查控件是否有任何错误并验证这是否是由于密码不匹配而不是必需的:

<div *ngIf="registerForm.get('confirmpwd').errors && registerForm.get('confirmpwd').errors['mismatchedPasswords']">
   Passwords do not match
</div>