You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular13实现确认密码验证报ValidatorFn类型不匹配错误

错误原因

触发该类型错误的核心原因有2个:

  • Angular 对ValidatorFn(验证器函数)类型有强制校验规则:自定义验证函数必须接收AbstractControl类型入参,且返回值必须是ValidationErrors | null(验证失败返回错误对象,验证通过返回null)。
  • 你编写的mustMatch密码验证器不符合上述类型规范:
    • 内部返回的验证函数入参直接声明为FormGroup类型,和ValidatorFn要求的AbstractControl入参类型不兼容
    • 函数逻辑分支中存在空return语句,实际返回值为undefined,不符合返回值类型要求
      最终TypeScript判定你传入FormGroup配置项的验证器不匹配ValidatorFn类型,抛出对应类型错误。
修正方案

1. 修正自定义密码验证器的类型定义

补全验证器的类型声明,调整入参、返回值符合Angular验证器规范,修改后的代码如下:

import { AbstractControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';

export class PasswordValidators {
  static mustMatch(controlName: string, matchingControlName: string): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      // 该验证器仅用于FormGroup,将入参强转为FormGroup类型
      const formGroup = control as FormGroup;
      const targetControl = formGroup.controls[controlName];
      const matchingControl = formGroup.controls[matchingControlName];

      // 若确认密码控件已存在其他验证错误,直接返回null不重复处理
      if (matchingControl.errors && !matchingControl.errors['mustMatch']) {
        return null;
      }

      // 值不匹配时设置错误并返回错误对象,匹配时清除错误返回null
      if (targetControl.value !== matchingControl.value) {
        matchingControl.setErrors({ mustMatch: true });
        return { mustMatch: true };
      } else {
        matchingControl.setErrors(null);
        return null;
      }
    };
  }
}

修改点说明:

  • 显式声明mustMatch方法返回值为ValidatorFn类型,TypeScript会自动校验内部函数的类型合规性
  • 验证器入参统一使用AbstractControl类型(符合ValidatorFn的入参要求),内部再转换为FormGroup操作控件,避免类型不兼容
  • 所有逻辑分支都明确返回ValidationErrors对象或null,删除空return语句,避免返回undefined

2. FormGroup代码无需额外改动

验证器修正完成后,你原有的FormGroup初始化代码会自动通过类型校验,无需修改:

registerForm = new FormGroup(
  {
    age: new FormControl('', [Validators.required, Validators.min(14)]),
    name: new FormControl('', [Validators.required, Validators.pattern('[a-zA-Z]')]),
    username: new FormControl('', [
      Validators.required,
      Validators.minLength(10),
      UsernameValidators.cannotContainSpace,
    ]),
    password: new FormControl('', [Validators.required, Validators.minLength(8)]),
    confirmPassword: new FormControl('', [Validators.required]),
  },
  { validators: PasswordValidators.mustMatch('password', 'confirmPassword') }
);

内容的提问来源于stack exchange,提问作者Axis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 07:15:41