How to Validate FormArray length in angular2

后端 未结 6 1608
猫巷女王i
猫巷女王i 2021-02-02 09:16

I have a data driven form in angular2 like below

this.formBuilder.group({
  \'name\': [\'\',Validators.required],
  \'description\': [\'\', Validators.required],         


        
6条回答
  •  自闭症患者
    2021-02-02 09:57

    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.

提交回复
热议问题