我只想在提供地址时验证电子邮件地址。 根据我的理解,您通过订阅valueChanges函数并根据提供的逻辑附加验证器来完成此操作。 但是,当我这样做时,验证器不会在正确的时间触发。 一个空字符串将被设置为无效,但单个字符将被标记为有效。
我的示例代码,来自模板:
<form [formGroup]="formGroup"> Email: <input formControlName="email" type="text"> </form>并从组件:
public ngOnInit(): void { this.formGroup = this._formBuilder.group({ email: new FormControl() }); this.formGroup.get('email').valueChanges.subscribe(value => { if (value.length > 0) { this.formGroup.get('email').setValidators(Validators.email); } else { this.formGroup.get('email').clearValidators(); } this.formGroup.updateValueAndValidity(); }); }你可以在这里看到它的行动: https : //plnkr.co/edit/5RiNDFKrTJ5iHJfVtmU5
I want to validate an email address only if the address is provided. From my understanding, you do this by subscribing to the valueChanges function and attach validators according to the provided logic. However, when I do this the validator does not fire at the correct time. An empty string will be set as invalid but a single character will be marked as valid.
My example code, from the template:
<form [formGroup]="formGroup"> Email: <input formControlName="email" type="text"> </form>And from the component:
public ngOnInit(): void { this.formGroup = this._formBuilder.group({ email: new FormControl() }); this.formGroup.get('email').valueChanges.subscribe(value => { if (value.length > 0) { this.formGroup.get('email').setValidators(Validators.email); } else { this.formGroup.get('email').clearValidators(); } this.formGroup.updateValueAndValidity(); }); }You can see it in action here: https://plnkr.co/edit/5RiNDFKrTJ5iHJfVtmU5
最满意答案
在文档AbstractControl.updateValueAndValidity中说它会更新其祖先的有效性。 在这种情况下,在父FormGroup上调用它不会更新子电子邮件控件。
解决方案应该是在电子邮件控件本身上调用updateValueAndValidity ,但是如果发生这种情况,则会导致valueChanges接收新值,这会导致无限循环。 通过传递选项{emitEvent: false}它应该绕过valueChanges并按预期行事。
this.formGroup.get('email').valueChanges.subscribe(value => { if (!this.formGroup.get('email').value) { this.formGroup.get('email').clearValidators(); } else { this.formGroup.get('email').setValidators(Validators.email); } this.formGroup.get('email').updateValueAndValidity({emitEvent: false}); });In the documentation AbstractControl.updateValueAndValidity says that it will update the validity of its ancestors. Calling it on the parent FormGroup does not appear to update the child email control in this case.
The solution should be to call updateValueAndValidity on the email control itself but when that happens it will cause valueChanges to receive a new value, which will result in an infinite loop. By passing the option {emitEvent: false} it should bypass valueChanges and behave as expected.
this.formGroup.get('email').valueChanges.subscribe(value => { if (!this.formGroup.get('email').value) { this.formGroup.get('email').clearValidators(); } else { this.formGroup.get('email').setValidators(Validators.email); } this.formGroup.get('email').updateValueAndValidity({emitEvent: false}); });更多推荐
发布评论