I have a data driven form in angular2 like below
this.formBuilder.group({
\'name\': [\'\',Validators.required],
\'description\': [\'\', Validators.required],
Good and clear way to do this is :
Create a Array.validator.ts
and put all the custom validations over there , like minLength
, maxLength
etc
import { ValidatorFn, AbstractControl, FormArray } from '@angular/forms';
// Array Validators
export class ArrayValidators {
// max length
public static maxLength(max: number): ValidatorFn | any {
return (control: AbstractControl[]) => {
if (!(control instanceof FormArray)) return;
return control.length > max ? { maxLength: true } : null;
}
}
// min length
public static minLength(min: number): ValidatorFn | any {
return (control: AbstractControl[]) => {
if (!(control instanceof FormArray)) return;
return control.length < min ? { minLength: true } : null;
}
}
}
And Then just import that file and use validation wherever you want to :
import { ArrayValidators } from './array.validator'; // Import it
'hobbies':new FormArray([],ArrayValidators.minLength(2)) // Use it
WORKING DEMO
Note :
You can directly use this package also ng-validator ( Reference is taken from this package ) , But If you need just required array validations you can do it like above.