Sub topic 9
Validation for entries and for the whole array
This chapter assumes you know FormControl, FormGroup, Validators, and how to bind a FormArray with formArrayName. It covers the two levels at which a FormArray is validated and the mistakes people make at each level.
Two levels of validation
A FormArray is validated at two levels:
- Entry validators sit on each child control or group, such as
Validators.requiredon a name field. They judge one value. - Array validators sit on the
FormArrayitself. They judge the list, for example "at least one entry" or "no duplicates".
Validity flows upward. If any child is invalid, the array is invalid, and so is the parent form. Errors do not flow upward. The array's errors object holds only the errors from its own validators, not those of its children.
Entry validators
Pass validators when you create each control. A common trap is Validators.email alone, which accepts an empty string. Pair it with Validators.required.
createEmail(value = '') {
return this.fb.control(value, [Validators.required, Validators.email]);
}Array validators
An array validator receives the FormArray as an AbstractControl and returns null when valid or an error object when not. This one rejects duplicate values:
import { AbstractControl, FormArray, ValidationErrors } from '@angular/forms';
export function minItems(min: number) {
return (control: AbstractControl): ValidationErrors | null => {
const length = (control as FormArray).length;
return length >= min ? null : { minItems: { required: min, actual: length } };
};
}
export function uniqueValues(control: AbstractControl): ValidationErrors | null {
const values = (control as FormArray).value as string[];
const lowered = values.map((v) => v.trim().toLowerCase());
return new Set(lowered).size === lowered.length ? null : { duplicates: true };
}Attach one or several validators as the second argument to fb.array. Angular re-runs them whenever a child value changes or the list changes through push, insert, removeAt or clear. You do not need to call updateValueAndValidity() yourself after those methods.
A complete example
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { minItems, uniqueValues } from './validators';
@Component({
selector: 'app-email-list',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<div formArrayName="emails">
@for (email of emails.controls; track email; let i = $index) {
<input [formControlName]="i" placeholder="Email" />
@if (email.touched && email.invalid) {
<small>Enter a valid email.</small>
}
<button type="button" (click)="emails.removeAt(i)">Remove</button>
}
</div>
@if (emails.hasError('minItems')) {
<p>Add at least one email.</p>
}
@if (emails.hasError('duplicates')) {
<p>Emails must be unique.</p>
}
<button type="button" (click)="emails.push(createEmail())">Add</button>
<button type="submit">Save</button>
</form>
`,
})
export class EmailListComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
emails: this.fb.array([this.createEmail()], [minItems(1), uniqueValues]),
});
get emails() {
return this.form.controls.emails;
}
createEmail(value = '') {
return this.fb.control(value, [Validators.required, Validators.email]);
}
submit() {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
console.log(this.form.getRawValue());
}
}Two details matter here. The entry message checks email.touched, so users do not see errors on a row they have not visited. markAllAsTouched() on submit makes every hidden error appear at once.
Common errors
- Reading child errors from the array.
emails.errorsnever contains an entry'semailerror. Checkemails.controls[i].errors, or useemails.hasError('email', [i]). - Casting without thinking. The array validator assumes a
FormArray. If you reuse it on aFormGroup,lengthisundefinedand the check passes silently. - Disabled controls. A disabled entry is skipped when computing
valueand validity. Thevalueof the array then differs fromgetRawValue(), and a duplicate check onvaluewill miss disabled rows.
Exercise
A FormArray has the validator minItems(2) and holds two entries. The user removes one with removeAt(0). Do you need to call updateValueAndValidity() for the "minItems" error to appear?
Show answer
No. removeAt (like push, insert and clear) re-runs the array's validators itself, so emails.hasError('minItems') becomes true right away.