Dom*_*čič 3 validation angular angular5
我有这个FormGroup
defaultIdNumberValidator = [Validators.required, Validators.minLength(6),
Validators.maxLength(11)];
this.registerForm = this.formBuilder.group({
permissions: this.formBuilder.group({
country: ['', [Validators.required]],
identityNumber: [null, this.defaultIdNumberValidator],
}, {validator: [this.validateId]})
});
Run Code Online (Sandbox Code Playgroud)
我想identityNumber根据this.validateId方法中的某些条件清除并添加验证器。
validateId(input: AbstractControl) {
if(condition) {
input.get("identityNumber").clearValidators(); //this is working
}
if(condition) {
input.get("identityNumber").setValidators(this.defaultIdNumberValidator); //not working
}
}
Run Code Online (Sandbox Code Playgroud)
当setValidators方法被调用时,我得到这个错误(行:109是setValidators被调用的行)
ERROR TypeError: Cannot read property 'defaultIdNumberValidator' of undefined
at RegisterComponent.validateId (register.component.ts:109)
at eval (forms.js:742)
at Array.map (<anonymous>)
at _executeValidators (forms.js:742)
at eval (forms.js:694)
at eval (forms.js:742)
at Array.map (<anonymous>)
at _executeValidators (forms.js:742)
at eval (forms.js:694)
at eval (forms.js:742)
Run Code Online (Sandbox Code Playgroud)
更新:
我重新启动开发服务器,现在出现此错误
ERROR TypeError: Cannot read property 'setValidators' of undefined
at RegisterComponent.validateId (register.component.ts:109)
at eval (forms.js:742)
at Array.map (<anonymous>)
at _executeValidators (forms.js:742)
at eval (forms.js:694)
at eval (forms.js:742)
at Array.map (<anonymous>)
at _executeValidators (forms.js:742)
at eval (forms.js:694)
Run Code Online (Sandbox Code Playgroud)
更新2:
我创建了简单的代码重现器来重现错误。如果您首先单击输入,然后单击其他位置,则会出现输入错误。因此,当输入值的长度> = 2时应消除此错误,当输入值的长度> = 5时应再次可见。我也不知道为什么当输入值的长度为3而不是2时错误消失了...
You need to bind(this) to keep the context of this. Also you need to use updateValueAndValidity for the change of the validators to be updated. There we also need to not emit an event, if you were, this would case looping until your browser crashes. So change the following:
}, {validator: this.validateId.bind(this)})
Run Code Online (Sandbox Code Playgroud)
验证器将如下所示:
validateId(input: AbstractControl) {
// ...
if(...) {
input.get("identityNumber").clearValidators();
input.get("identityNumber").updateValueAndValidity({emitEvent:false, onlySelf:true});
}
if(...) {
input.get("identityNumber").setValidators(this.defaultIdNumberValidator);
input.get("identityNumber").updateValueAndValidity({emitEvent:false, onlySelf:true});
}
}
Run Code Online (Sandbox Code Playgroud)
您的朋克
| 归档时间: |
|
| 查看次数: |
7670 次 |
| 最近记录: |