不要在Angular2中验证未修改的字段 [英] Don't validate untouched fields in Angular2
问题描述
我有反应式表单,并且不希望在用户真正访问字段之前触发验证.
I have reactive form and don't want validation to be triggered until user really visits a field.
例如,这是一个字段:
<input type="text" [formControl]="customerNumber">
这是组件:
customerNumber: FormControl = new FormControl(
null, {validators: [Validators.required]
});
如您所见,它很简单.我遇到的问题是,显示表单并且输入字段获得ng-invalid
类时,即使未触摸 ,也会触发验证.
As you see, its simple. The issue I have is that validation is triggered when the form is displayed and the input field gets ng-invalid
class, even it is not touched.
我只需要在用户触摸字段后才触发验证.
I need validation to be triggered only after the user touches the field.
推荐答案
正如评论中提到的那样:
As somebody mentioned in the comments:
初始配置:
customerNumber: FormControl = new FormControl(null);
订阅值更改并仅在尚未设置验证器的情况下设置您的验证器:
Subscribe to value changes and set your validator only if a validator is not already set:
this.sub = this.form.controls.customerNumber.valueChanges.subscribe(value => {
if (!this.form.controls.customerNumber.validator) {
this.form.controls.customerNumber.setValidators(Validators.required);
}
})
如果您需要对触发验证器设置的值执行验证 请确保致电:
If you need to perform validation on the value that triggered validator setup make sure to call:
this.form.controls.customerNumber.updateValueAndValidity();
设置后立即
此外,在完成该组件后,请确保退订:
Also, make sure to unsubscribe once you are done with the component:
ngOnDestroy() {
this.sub.usubscribe();
}
编辑
另一种选择是创建一个自定义的必需验证器,该验证器仅在控件不干净时才进行验证.
Another option would be to create a custom required validator that validates only if the control is dirty.:
import { FormControl } from '@angular/forms';
function customRequiredValidator(c: FormControl) {
if(!c.dirty)
{
return null;
}
...
}
然后,您可以将其导入到任何需要的地方,并使用它代替Validators.required.
You can then just import it wherever needed and use it in place of the Validators.required.
这篇关于不要在Angular2中验证未修改的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!