Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding multiple validators to FormGroup in angular2

How can I add multiple validators to a FormGroup.

A FormControl can accept an array of validators, however a FormGroup cannot. Is there a workaround aside from creating a single custom validator?

I am using rc4.

like image 877
Maxim Avatar asked Jul 23 '16 11:07

Maxim


People also ask

How will you add validators in FormControl?

Adding async validators to reactive formslink To use an async validator in reactive forms, begin by injecting the validator into the constructor of the component class. Then, pass the validator function directly to the FormControl to apply it.


2 Answers

Multiple validators can be combined through Validators.compose().

From the api reference:

compose(validators: ValidatorFn[]) : ValidatorFn

Compose multiple validators into a single function that returns the union of the individual error maps.

like image 65
David Bulté Avatar answered Oct 12 '22 08:10

David Bulté


Actually, FormGroup did accept array of validators. Just that the interface not updated. Cast it to any will do. E.g.

<any>[Validators.required, Validators.minlength(2)]
like image 24
Chybie Avatar answered Oct 12 '22 09:10

Chybie