angular 2 重构服务中的自定义验证逻辑
angular 2 refactor custom validation logic in service
我有一个带有多个自定义验证器(下面只有一个)的密码 FormControl:
password = new FormControl('',
[Validators.required, Validators.minLength(8),
this.passwordHasLowerCaseValidator.bind(this)]);
passwordHasLowerCaseValidator(control: FormControl) {
return (...);
}
我想要从服务中调用自定义验证器来重构我的注册组件,例如
constructor(private customValidators:CustomValidators){}
password = new FormControl('',
[Validators.required, Validators.minLength(8),
this.customValidators.passwordHasLowerCaseValidator.bind(this)]);
我已经试过了,但它抛出了错误,我想表单要么无法访问它们,要么无法将数据传递给它..
谢谢!
如果您将验证器更改为 return 验证器函数,例如
passwordHasLowerCaseValidator(customValidators: CustomValidators) {
return (control: FormControl) => {
return (...);
// here you can access "customValidators"
}
}
并像
一样使用它
constructor(private customValidators:CustomValidators){}
password = new FormControl('',
[Validators.required, Validators.minLength(8),
this.customValidators.passwordHasLowerCaseValidator(customValidators).bind(this)]);
你应该得到想要的行为。
我有一个带有多个自定义验证器(下面只有一个)的密码 FormControl:
password = new FormControl('',
[Validators.required, Validators.minLength(8),
this.passwordHasLowerCaseValidator.bind(this)]);
passwordHasLowerCaseValidator(control: FormControl) {
return (...);
}
我想要从服务中调用自定义验证器来重构我的注册组件,例如
constructor(private customValidators:CustomValidators){}
password = new FormControl('',
[Validators.required, Validators.minLength(8),
this.customValidators.passwordHasLowerCaseValidator.bind(this)]);
我已经试过了,但它抛出了错误,我想表单要么无法访问它们,要么无法将数据传递给它..
谢谢!
如果您将验证器更改为 return 验证器函数,例如
passwordHasLowerCaseValidator(customValidators: CustomValidators) {
return (control: FormControl) => {
return (...);
// here you can access "customValidators"
}
}
并像
一样使用它constructor(private customValidators:CustomValidators){}
password = new FormControl('',
[Validators.required, Validators.minLength(8),
this.customValidators.passwordHasLowerCaseValidator(customValidators).bind(this)]);
你应该得到想要的行为。