10

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.

Maxim
  • 463
  • 1
  • 7
  • 17
  • 1
    Maybe via Validators.compose? – David Bulté Jul 23 '16 at 12:06
  • 2
    Yes that's what I'm trying to do but I get a weird error during compilation. Ex. `let myGroup = this.formBuilder.group({}, {validator: Validators.compose([this.myCustomValidator(variable1, variable2)])});` Just to give you an idea of what myCustomValidator does, it returns a validator function `return (group: FormGroup): {[s: string]: boolean} => {}` The error I get is: `Argument of type '((group: FormGroup) => { [s: string]: boolean; })[]' is not assignable to parameter of type 'ValidatorFn[]'.` – Maxim Jul 23 '16 at 14:51
  • Btw the custom validator by itself works fine like this: `let myGroup = this.formBuilder.group({}, {validator: this.myCustomValidator(variable1, variable2)});` – Maxim Jul 23 '16 at 15:06
  • @DavidBulte I was able to get it to work with Validators.compose after all. I was importing Validators from '@angular/core' instead of '@angular/forms'. If you post it as an answer I will accept it. – Maxim Jul 23 '16 at 15:14
  • Thx maxim.Glad it works. – David Bulté Jul 23 '16 at 17:53

2 Answers2

18

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.

Community
  • 1
  • 1
David Bulté
  • 2,769
  • 2
  • 27
  • 36
6

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)]
Chybie
  • 3,366
  • 16
  • 15
  • 2
    Just tried it, although it doesn't throw an error only one of the validators works for some reason. Do you use FormBuilder.group or just plain FormGroup? – Maxim Jul 26 '16 at 06:42
  • Did you find a solution to this? @Maxim – Pritesh Acharya Dec 06 '17 at 23:55
  • @PriteshAcharya I just ended up using Validators.compose(). Also keep in mind that this question was asked in regards to Angular RC4, it is now on Angular 4 or something, I've since moved on to Vue. – Maxim Dec 08 '17 at 01:23
  • I just used two validators (required, maxlength) and it worked for me – unkreativ May 22 '18 at 16:05