首页 > 解决方案 > 如何在 ngOnInit 方法中添加额外的验证器?

问题描述

我有一个角度组件,我正在向构造函数中的表单添加一些验证器。但是我想在我的 ngOnit 方法中添加额外的验证器。我怎样才能做到这一点?

   export class ResetPasswordComponent implements OnInit {
      constructor(
        private fb: FormBuilder,
        private route: ActivatedRoute,
        private forgotPasswordService: ForgotPasswordService,
        private configService: ConfigService,
        private usersService: UsersService
      ) {
        this.blacklistedPasswords = this.configService.config.blacklistedPasswords;

        this.formGroup = this.fb.group(
          {
            password: ['', [Validators.required, Validators.minLength(8)]],
            confirmPassword: ['', [Validators.required, Validators.minLength(8)]]
          },
          {
            validator: Validators.compose([
              passwordStrengthValidator('password', 'confirmPassword'),
              blacklistedPasswordValidator(
                'password',
                'confirmPassword',
                this.blacklistedPasswords
              )
            ])
          }
        );
      }


ngOnInit() {

}
    }

如何将另一个验证器附加到组件 ngOnInit 方法?例如,我想添加一个类似于 passwordStrengthValidator 和 blacklistedPasswordValidator 的验证器 matchingValidator('password', 'confirmPassword')。我怎样才能实现它?

我是 Angular 的新手,非常感谢

标签: angulartypescript

解决方案


因此,您可以像这样附加新的验证器:

ngOnInit() {
  this.formGroup.setValidators(Validators.compose([this.formGroup.validator, matchingValidator('password', 'confirmPassword')]));
}

您需要在此处传递所有现有验证器,因为setValidators会清除所有现有验证器,然后添加您传递的内容。希望有帮助。


推荐阅读