Search code examples
angularangular-reactive-forms

Add a Custom Validator globally, to all FormControls in the application


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?

Solution

  • 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.