Adding multiple validators to FormGroup in angular2
Asked Answered
J

3

11

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.

Justifiable answered 23/7, 2016 at 11:58 Comment(4)
Maybe via Validators.compose?Klansman
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[]'.Justifiable
Btw the custom validator by itself works fine like this: let myGroup = this.formBuilder.group({}, {validator: this.myCustomValidator(variable1, variable2)});Justifiable
@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.Justifiable
A
20

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.

Attorn answered 23/7, 2016 at 17:51 Comment(2)
documentation link is broken, but the answer still worksDisaccustom
doesn't work for me. { validator: Validators.compose( [ this.validationFn1.bind(this), this.validationFn2.bind(this) ] ) }Highflier
L
8

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)]
Lost answered 24/7, 2016 at 4:28 Comment(4)
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?Justifiable
Did you find a solution to this? @JustifiableHighflier
@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.Justifiable
I just used two validators (required, maxlength) and it worked for meSlavic
N
0

I had the same problem. I was using a FormGroup and a FormBuilder. this is how i set two validators for email input:

emailForm : FormGroup;
CreatEmailForm(){
this.emailForm = this.formBuilder.group({
emial:["[email protected]", { validators: [Validator.required , Validators.email ]}],
context:[null , Validator.required]})
}
Natatory answered 25/10, 2023 at 12:31 Comment(1)
Read the question carefully!Ungainly

© 2022 - 2024 — McMap. All rights reserved.