【问题标题】:validating one field with another field in angular reactive form以角度反应形式验证一个字段与另一个字段
【发布时间】:2021-07-28 13:06:35
【问题描述】:

我想要 Angular 最新版本的参考链接中相同示例的解决方案。在 Angular 10 或任何 Angular 版本中使用下拉验证值验证文本框。堆栈溢出中解决的参考链接How to validate textbox based on dropdown value in angularjs?

【问题讨论】:

标签: angular forms validation reactive


【解决方案1】:

我将针对类似的主题编写我的解决方案,您可以自己定制:

我检查密码字段是否相同:

  1. 创建验证器
export class PasswordConfirmationValidator {
   
   static checkPasswordsAreTheSame(formGroup: FormGroup): ValidationErrors | null {
       const password = formGroup.get('password')?.value;
       const confirmPassword = formGroup.get('confirmPassword')?.value;
       
       if (password !== confirmPassword) {
           return {
               notTheSame: true
           };
       }
       return null;
   }
}

  1. 将此验证器添加到表单:
this.formGroup = this.formBuilder.group({
            password: [null, [Validators.required]],
            confirmPassword: [null, [Validators.required]]
        }, {
            validators: PasswordConfirmationValidator.checkPasswordsAreTheSame
        });

由于验证器可以访问整个表单,因此您可以获得任何控制权并使用它

【讨论】:

    猜你喜欢
    • 2018-12-28
    • 2022-11-03
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多