英文:
Add a Custom Validator globally, to all FormControls in the application
问题
我们有一个客户提出了一个想法,即在他们的应用程序中的每个字段上都添加一个自定义验证器,该应用程序包含1000多个Angular formControls。
我的问题是:是否有一种方法可以全局修改所有formControls
的行为,而不必手动逐个将此验证器添加到这一千个formControls中?
- 编写一个自定义验证器可以解决问题,但手动添加它
myField: ['', [Validators.required, mySpecialValidator]]
是一项相当繁琐的任务,我们想要避免这样做。 - ChatGPT建议编写一个指令并将其应用于HTML模板,但我与以前一样陷入了同样的情况;我仍然需要修改一千个输入字段。是否有一个库或技巧可以允许全局修改所有formControls的行为?
英文:
We have a client who came up with the idea of adding a custom validator to EVERY field in their application, which contains over 1000 Angular formControls.
My question is: is there a way to globally modify the behavior of all formControls
without manually and individually adding this validator to each of the thousand formControls?
- Writing a custom validator works, but adding it manually
myField: ['', [Validators.required, mySpecialValidator]]
is quite the tedious task which we want to avoid.
- ChatGPT suggested writing a directive and applying it to the HTML template, but I'm in the same situation as before; I still need to modify a thousand input fields. Is there a library or trick that allows for global modification of the behavior of all formControls?
答案1
得分: 1
以下是翻译好的部分:
"不能为每个表单控件定义全局验证器的方法,但我们可以在每个表单上添加自定义验证器(而不是表单控件)。
这种方法比在每个表单控件上添加验证要轻松一些,控件可能有1000个,但表单可能较少,所以我会选择在每个表单上使用自定义验证器。
const myForm = new FormGroup({
'myField': new FormControl(),
...
}, { validators: mySpecialValidator });
希望这解决了您的问题。"
英文:
There is no way to define a global validators for each form control, however we can add a custom validator on each form (not form control).
This approach is less hectic than adding validation on each form control, controls can be 1000 but form could be fewer so I would go with custom validator on each form.
const myForm = new FormGroup({
'myField': new FormControl(),
...
}, { validators: mySpecialValidator });
Hope this address your issue.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论