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