Search code examples
angularformsangular-reactive-forms

In Angular, how to add Validator to FormControl after control is created?


We have a component that has a dynamically built form. The code to add a control with validators might look like this:

var c = new FormControl('', Validators.required);

But let's say that I want to add 2nd Validator later. How can we accomplish this? We cannot find any documentation on this online. I did find though in the form controls there is setValidators

this.form.controls["firstName"].setValidators 

but it is not clear how to add a new or custom validator.


Solution

  • You simply pass the FormControl an array of validators.

    Here's an example showing how you can add validators to an existing FormControl:

    this.form.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);
    

    Note, this will reset any existing validators you added when you created the FormControl.

    Angular 12 update

    Since Angular 12, if you want to add new validators to the form without removing the existing validators, you can use addValidator:

    this.form.controls["firstName"].addValidators([Validators.minLength(1), Validators.maxLength(30)]);