angular - 如何在 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 的新手,非常感谢
解决方案
因此,您可以像这样附加新的验证器:
ngOnInit() {
this.formGroup.setValidators(Validators.compose([this.formGroup.validator, matchingValidator('password', 'confirmPassword')]));
}
您需要在此处传递所有现有验证器,因为setValidators会清除所有现有验证器,然后添加您传递的内容。希望有帮助。
推荐阅读
- c# - 每当对 cshtml 进行更改而不重建项目时,Razor Page 都会引发错误
- django - Django 使用模型提交的表单数据创建不同模型的新实例
- r - 计算数据框中所有非数字列的模式
- html - 如何在 bootstrap v4.1 中降低导航栏的高度
- c# - Angular 6 与 Asp.net Core 2.1 不存在“Access-Control-Allow-Origin”标头
- python - 最大奇数 Python 代码简化
- html - 容器上的最小高度以允许子 div 拉伸阻止空的兄弟 div 扩展
- python - 选择内层索引数据
- python - Python MySQLdb自定义函数错误
- ios - 我怎么知道我不能提交 iPhone 应用到应用商店的原因?