Angular custom validation for FormArray fields (Reactive Form)

Issue

I am new to Angular and would like to check how do I go about performing custom field validation for FormArray?

The FormArray is dynamic where you can push or remove FormGroup items. The FormGroup consists of field1, field2, field3. If either one of the field is not null, the other fields should be set with validators.required. The form will be valid if all fields are either null or filled.

Thanks.

Below is the code sample:

formA!: FormGroup;

initializeForm(): void {
    this.formA = this.fb.group({
      item1: this.fb.array([this.createItem1()]),
      item2: this.fb.array([this.createItem2()]),
    });
  }

createItem1(): FormGroup {
   return this.fb.group({
       field1: null,
       field2: null,
       field3: null,
   });
}

Solution

Try this.

createItem1(): FormGroup {
  const fg = this.fb.group({
      field1: null,
      field2: null,
      field3: null,
  });
   
  const validatorFn = (control: AbstractControl): { [key: string]: any } | null => {
    const obj = fg.getRawValue();
     
    if (obj.field1 || obj.field2 || obj.field3) {
      return Validators.required(control);
    }
     
    return null;
  };
   
  for (const control of Object.values(fg.controls)) {
    control.setValidators(validatorFn);
  }

  return fg;
}

Also you will need to execute updateValueAndValidity() for all controls when key pressed.

Answered By – N.F.

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published