Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 937
melegant Avatar asked Aug 05 '16 20:08

melegant


People also ask

How do you add validators in FormControl?

We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.

How do I add validators in FormArray?

Validating Angular FormArray First you need to add the required validators while creating a new product form group inside the addProduct method. Now let's add a span element adjacent to the input control. Add the following CSS to the app. component.

How can you add the validator function into the reactive forms?

A validator function returns true if the form field is valid according to the validator rules, or false otherwise. A validator can be plugged in directly into a reactive form simply by adding it to the validators list. Each form field has its own list of separate validators.


1 Answers

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)]); 
like image 158
Andy-Delosdos Avatar answered Oct 20 '22 06:10

Andy-Delosdos