Search code examples
angularangular-reactive-formsangular-forms

Using built-in Angular Validators on a FormArray


Using FormBuilder, I instantiate a FormArray for an array of email fields. I assign it a set of Validators, which includes a custom Validator, and Angular's built-in Validators.email.

this.formBuilder.array(
    [this.formBuilder.control('')], 
    Validators.compose([customValidator, Validators.email])
)

Assigning the Validators in this way means that the FormArray is passed as the control parameter to the Validators. My custom validator can be tuned to expect a FormArray, but Validators.email expects a FormControl with a single value.

How do I use Angular built-in Validators with a FormArray?


Solution

  • formbuild array method specify that validatorOrOpts or asyncValidator parameters gone to run on the form array itself not the controls of the array so there are two solution

    1. add the validator to the control it self

         this.formBuilder.array(
          [this.formBuilder.control('',Validators.email)], 
          Validators.compose([customValidator])
      )
      
    2. create a custom validator and trigger angular validator on each array controls
    function customArrayEmailValidator(formArray: FormArray) {
      if (formArray.length > 0) {
        for (let c of formArray.controls) {
          let state = Validators.email(c)
          if (state !== null) {
            return { emailInValid: state }
          }
        }
        return null;
      } else {
        return null;
      }
    }
    

    but it 's still look the same like the first way

    stackblitz demo

    FormBuilder - Array