我有一个角度组件,我正在构造函数中向表单添加一些验证器。但是我想在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')。我该如何实现?
我是一个新手,非常感谢您
答案 0 :(得分:0)
因此,您可以像这样添加新的验证器:
ngOnInit() {
this.formGroup.setValidators(Validators.compose([this.formGroup.validator, matchingValidator('password', 'confirmPassword')]));
}
您需要在此处传递所有现有的验证器,因为 setValidators 会清除所有现有的验证器,然后添加您传递的内容。希望有帮助。