I have a data driven form in angular2 like below
this.formBuilder.group({
'name': ['',Validators.required],
'description': ['', Validators.required],
'places': this.formBuilder.array([], Validators.minlength(1))
})
I want to add validations to the place
formArray, so i am adding minlength
validation, but minlength validation is not working on formArray.
What are the other validations for formArray, so that form must be valid only when places array contain atleast one place.
because you using wrong validator function name:
minlength
->minLength
demo code:
Plunker: https://plnkr.co/edit/cfi7nN?p=preview
Add this custom validator to your validation service:
And then when creating the form do the following:
And you can check errors against the
FormArray
by checkingFormArray.hasError('minLengthArray')
if you are trying to add validation to formarray try this may help you,
this
initPlaces
will simply return formGroup with validation as per requirement.Good and clear way to do this is :
Create a
Array.validator.ts
and put all the custom validations over there , likeminLength
,maxLength
etcAnd Then just import that file and use validation wherever you want to :
WORKING DEMO
Validators.required
does the magic for you: