1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

The first solution is unfortunate, because of course that would have to be applied for every individual control added to the array. I guess the second solution works as well as it possibly can, if less clean than some Angular built-in way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.