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

Angular表单交叉验证后无法在模板中获取密码不匹配notSame错误

Angular 12 表单密码交叉校验无法获取notSame错误解决方案

问题根因

你将pwdMatchValidator绑定为FormGroup级校验器,校验器返回的{notSame: true}错误会挂载在整个FormGroup实例(也就是你代码里的restrict对象)的errors属性中,不会自动同步到confirmPassword单个表单控件的errors里,所以从confirmPassword上读取notSame错误自然拿不到结果。
另外你模板中confirmPassword.hasError('notSame', 'passwords')的第二个参数填写错误,你没有名为passwords的父级表单控件,所以该判断永远返回false。

解决方案1:直接从FormGroup读取错误(最简单)

不需要修改组件校验逻辑,仅调整模板的错误判断条件即可,同时建议增加控件touched判断优化输入体验:

<p-password formControlName="confirmPassword"></p-password>
<small class="p-error" *ngIf="confirmPassword.hasError('required')">No puede estar vacio</small>
<small class="p-error" *ngIf="confirmPassword.hasError('minlength')">Debe ser de hasta 6 caracteres.</small>
<!-- 从整个FormGroup读取notSame错误,同时仅在确认密码控件被操作过才提示 -->
<small class="p-error" *ngIf="restrict.hasError('notSame') && confirmPassword.touched">Las contraseñan son diferentes.</small>
<button pButton pRipple label="Save" icon="pi pi-check" class="p-button-text" [disabled]="!restrict.valid"></button>

此时你要读取notSame状态,直接通过restrict.errors?.notSame即可。

解决方案2:将错误挂载到confirmPassword控件(适合需要统一管理单控件错误的场景)

修改校验器逻辑,手动给confirmPassword控件设置/清除notSame错误:

pwdMatchValidator(frm: FormGroup) {
  const pass = frm.get('newPassword').value;
  const confirmPass = frm.get('confirmPassword').value;
  const confirmControl = frm.get('confirmPassword');

  if (pass !== confirmPass) {
    // 密码不一致时给确认密码控件添加notSame错误
    confirmControl.setErrors({ notSame: true });
    return null;
  } else {
    // 密码一致时清除对应错误
    if (confirmControl?.errors?.['notSame']) {
      delete confirmControl.errors['notSame'];
      // 如果控件没有其他错误则重置errors为null
      if (Object.keys(confirmControl.errors).length === 0) {
        confirmControl.setErrors(null);
      }
    }
    return null;
  }
}

修改后你原来的confirmPassword.hasError('notSame')判断就可以正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:15:06