Sub topic 9
Validation for entries and for the whole array
This chapter assumes you can write a standalone component that imports ReactiveFormsModule. It also assumes you know FormControl, FormGroup, built-in Validators, and how to add and remove controls in a FormArray. Here you will attach validators at two levels: to each entry and to the array itself. You will also see how the results combine.
Two levels of validation
A FormArray is a control, so it has its own errors and status, like any other control. A form with a dynamic list has two kinds of rules:
- Entry rules describe one item. Examples: an email must be well formed, a quantity must be at least 1.
- Array rules describe the list as a whole. Examples: at least one item must exist, no two items may share a name.
Entry validators belong on the entry controls or groups. Array validators belong on the FormArray. Each validator sees only the control it is attached to.
Validity propagates upward
A parent control is invalid if any child is invalid, or if its own validators fail. The parent's errors object contains only errors from its own validators. It never contains child errors.
This has a practical consequence. form.invalid is true when any row is bad or when the array rule fails. To tell which case you are in, check items.errors for array-level problems and the individual controls for entry-level problems.
Validating entries
Entry validators work as in a plain FormGroup. Put them in the factory that creates each row, so every row, whether created at startup, by an "Add" button, or from loaded data, gets the same rules.
createItem(name = '', quantity = 1) {
return this.fb.group({
name: [name, [Validators.required, Validators.maxLength(40)]],
quantity: [quantity, [Validators.required, Validators.min(1)]],
});
}Keeping the rules in one factory is the main design point. If you scatter new FormControl(...) calls with different validators across ngOnInit, addItem and a data-loading method, the rows drift apart.
For a list of plain controls, as in the email example, pass validators to each control:
import { FormArray, FormControl, Validators } from '@angular/forms';
const emails = new FormArray([
new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.email] }),
]);Validating the array itself
A validator for the array is an ordinary validator function. It receives the control, which is the FormArray, and returns null when valid or an error object when not.
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 } };
};
}
// Usage: this.fb.array([this.createItem()], minItems(1))The cast control as FormArray is safe only if you attach the validator to a FormArray. If someone attaches it to a FormControl, length is undefined and the comparison is false, so the validator reports an error. The sample reports the error object in the same format as built-in validators: a key naming the rule, and a value with details.
Counting length, not value
Use control.length, not control.value.length. A FormArray's value leaves out disabled children. If you disable a row, value.length shrinks but length does not. Decide which you mean. For "at least one row exists" use length. For "at least one enabled row" use value.length or getRawValue().length deliberately.
Built-in Validators.minLength and Validators.maxLength also work on a FormArray, because they read the length of the control's value. They therefore have the disabled-row behavior described above.
Rules across entries
Some rules involve several rows at once, such as "names must be unique". No single row can check this, because it cannot see its siblings. Put the validator on the array, where all rows are visible.
import { AbstractControl, FormArray, ValidationErrors, ValidatorFn } from '@angular/forms';
export function uniqueNames(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const names = (control as FormArray).controls
.map((row) => String(row.get('name')?.value ?? '').trim().toLowerCase())
.filter((name) => name !== '');
const duplicates = names.filter((name, index) => names.indexOf(name) !== index);
return duplicates.length > 0
? { duplicateNames: [...new Set(duplicates)] }
: null;
};
}The validator ignores empty names, so that required reports them and uniqueNames does not flag two blank rows as duplicates. Normalizing with trim().toLowerCase() makes "Pen" and " pen " collide, which is usually what users expect.
Attach both array validators with the options form of fb.array:
items = this.fb.array([this.createItem()], {
validators: [minItems(1), uniqueNames()],
});The array runs all its validators and merges the error objects. If both fail, items.errors has both minItems and duplicateNames.
When validators run
Angular re-runs the array's validators when:
- the value of any child changes, because the change bubbles up to the parent;
- you call
push,insert,removeAt,setControlorclear, which each update the array's validity.
You do not need to call anything after addItem() or removeItem(). The minItems error appears the moment the last row is removed.
You do need to act when you change validators on an existing control. setValidators does not re-run them, so follow it with updateValueAndValidity():
const quantity = row.controls.quantity;
quantity.setValidators([Validators.required, Validators.min(10)]);
quantity.updateValueAndValidity();The same holds if a validator depends on outside state, such as a maximum stock level that changes. The form does not know the state changed, so you must trigger re-validation.
Showing errors in the template
Display entry errors next to the field, and array errors near the list. Gate entry errors on touched or dirty so a fresh row does not start covered in red text.
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { minItems, uniqueNames } from './validators';
@Component({
selector: 'app-order-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<div formArrayName="items">
@for (item of items.controls; track item; let i = $index) {
<div [formGroupName]="i">
<input formControlName="name" placeholder="Name" />
@if (item.controls.name.touched && item.controls.name.hasError('required')) {
<span class="error">Name is required.</span>
}
<input type="number" formControlName="quantity" />
@if (item.controls.quantity.touched && item.controls.quantity.hasError('min')) {
<span class="error">Quantity must be at least 1.</span>
}
<button type="button" (click)="removeItem(i)">Remove</button>
</div>
}
</div>
@if (items.hasError('minItems')) {
<p class="error">Add at least one item.</p>
}
@if (items.errors?.['duplicateNames']; as dupes) {
<p class="error">Duplicate names: {{ dupes.join(', ') }}</p>
}
<button type="button" (click)="addItem()">Add item</button>
<button type="submit" [disabled]="form.invalid">Submit</button>
</form>
`,
})
export class OrderFormComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
items: this.fb.array([this.createItem()], {
validators: [minItems(1), uniqueNames()],
}),
});
get items() {
return this.form.controls.items;
}
createItem(name = '', quantity = 1) {
return this.fb.group({
name: [name, [Validators.required, Validators.maxLength(40)]],
quantity: [quantity, [Validators.required, Validators.min(1)]],
});
}
addItem() {
this.items.push(this.createItem());
}
removeItem(index: number) {
this.items.removeAt(index);
}
submit() {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
console.log(this.form.getRawValue());
}
}Two details matter here. First, hasError('minItems') on the array checks only the array's own errors, which is what you want for a message about the list. Second, markAllAsTouched() walks every row, so a user who presses Submit without touching anything sees all entry errors at once.
A disabled submit button is convenient, but it hides the reason. Consider leaving the button enabled and showing the messages after markAllAsTouched(), as submit() does above.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Putting a uniqueness check on each row | A row cannot see its siblings, so the rule never works | Put it on the `FormArray` |
| Reading `items.errors` to find a bad row | It is `null` when only a row is invalid | Check the row's controls, or `items.invalid` |
| Using `value.length` for a minimum count | Disabled rows are ignored | Use `control.length` |
| Calling `setValidators` without `updateValueAndValidity()` | Old validity remains | Call `updateValueAndValidity()` |
| Different validators in several row-creating places | Rows validate inconsistently | Use one factory such as `createItem` |
Exercise
A user adds two rows and types "Pen" in one and "pen" in the other. Your form uses the uniqueNames validator on the array, but the page shows no error and form.invalid is false. The row controls are all valid. What is the most likely cause, and how do you check it?
Show answer
The validator is probably attached to the wrong control, for example to each row's name control or to the parent FormGroup, instead of to the FormArray, so it never sees all rows. Check with console.log(this.items.errors). It should contain duplicateNames. If it is null, move the validator to the fb.array(..., { validators: [...] }) options. Also confirm that the validator lower-cases and trims names, because without that "Pen" and "pen" would not match.
Exercise
You add a maxItems(5) validator to the array. After the user adds a sixth row, the error shows. After they remove one row, will the error disappear without extra code, and why?
Show answer
Yes. removeAt updates the array's value and validity, so the array re-runs its validators and maxItems returns null once the length is 5. No manual call to updateValueAndValidity() is needed.