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

如何在Angular中不使用第三方库实现新密码与确认密码的比对校验

Angular模板驱动表单密码一致性实时校验实现方案

不需要引入任何第三方库,通过Angular原生自定义校验指令即可实现,操作步骤如下:


步骤1:创建自定义密码比较校验指令

新增一个compare-validator.directive.ts文件,写入以下代码:

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl } from '@angular/forms';

@Directive({
  selector: '[compare]',
  providers: [{
    provide: NG_VALIDATORS,
    useExisting: CompareValidatorDirective,
    multi: true
  }]
})
export class CompareValidatorDirective implements Validator {
  // 接收传入的要对比的目标控件的模板引用名
  @Input() compare: string;

  validate(control: AbstractControl): { [key: string]: any } | null {
    // 获取目标控件实例
    const targetControl = control.root.get(this.compare);
    // 两个控件都有值且值不相等时返回校验错误
    if (targetControl && control.value && targetControl.value !== control.value) {
      return { compare: true };
    }
    return null;
  }
}

该指令会自动校验当前控件值和你指定的目标控件值是否一致,不一致时返回compare错误,匹配你现有模板中写的错误提示逻辑。


步骤2:在对应模块中注册指令

打开你当前页面所属的模块文件,把上面创建的指令加到declarations配置中,这样模板才能识别compare属性:

import { CompareValidatorDirective } from './compare-validator.directive';

@NgModule({
  declarations: [
    // 你原有的组件、指令声明
    CompareValidatorDirective
  ],
  // 其他模块配置保持不变
})
export class YourPageModule { }

步骤3:修改模板实现实时触发校验

找到你新密码的input输入框,新增一个input事件,修改后代码如下:

<input type="password" class="form-control" pattern="^(?=.*[A-Za-z])(?=.*\d).{8,}$" required
    [class.is-invalid]="newpassword.invalid && newpassword.touched" name="newpasswords"
    #newpassword="ngModel" [(ngModel)]="changepassword.newPassword"
    placeholder="New Password"
    <!-- 新增这行,新密码修改时实时触发确认密码的重新校验 -->
    (input)="repassword.control.updateValueAndValidity()">

实现效果

现在即可实现实时校验:

  • 输入确认密码时会自动和新密码比对,不一致时立刻显示「Confirm password do not match」提示
  • 修改已经填写完成的新密码时,也会自动触发确认密码的校验状态更新,不会出现新密码改了但确认密码校验结果不更新的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:15:03