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

Angular自定义密码确认校验器异常:修改原密码后字段残留错误

问题原因
  • 你的自定义交叉校验器仅在两次输入密码不匹配时,给passwordConfirm字段手动设置了matching错误,但是在两次输入一致的分支逻辑中,只给表单组返回了校验通过的null值,没有清理之前手动挂载到passwordConfirm字段上的matching错误,导致字段级别的错误残留。
  • 修改确认密码字段时能正常消除错误的原因是:修改确认密码时会触发该字段自身的校验重新计算,而修改原密码字段时,仅会触发表单组的交叉校验,不会触发确认密码字段自身的错误重算,所以之前设置的matching错误就一直留存在确认密码字段上。
修复方案

修改自定义校验器的逻辑,当两次密码匹配时,主动清除确认密码字段上的matching错误,同时保留该字段其他固有错误(比如必填校验错误),修改后的代码如下:

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

export class Validation {
  static match(controlName: string, checkControlName: string): ValidatorFn {
    return (controls: AbstractControl) => {
      const control = controls.get(controlName);
      const checkControl = controls.get(checkControlName);

      if (checkControl?.errors && !checkControl.errors.matching) {
        return null;
      }

      if (control?.value !== checkControl?.value) {
        checkControl?.setErrors({ matching: true });
        return { matching: true };
      } else {
        // 新增逻辑:清除checkControl上的matching错误,保留其他错误
        if (checkControl?.errors) {
          delete checkControl.errors.matching;
          // 如果删除后无其他错误,将errors重置为null
          if (Object.keys(checkControl.errors).length === 0) {
            checkControl.setErrors(null);
          }
        }
        return null;
      }
    };
  }
}

可选优化:可以将模板中密码不匹配的错误判断逻辑,从读取表单组错误改为读取确认密码字段的错误,逻辑对应更合理:

<kendo-formerror *ngIf="signupForm.controls.passwordConfirm.errors?.matching">A két jelszó nem egyezik</kendo-formerror>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:39:00