Sub topic 4
Attaching validators to controls and groups
This chapter assumes you know TypeScript functions and types, Angular components and templates, and the basics of reactive forms (FormControl, FormGroup). You should also have read the previous chapters on the validator function contract and on returning ValidationErrors or null. Here you wire validators into a form.
Where validators attach
A validator does nothing until you attach it to an AbstractControl. Every FormControl, FormGroup, and FormArray accepts validators. The control runs them whenever its value changes and stores the result in its errors property and its status.
Where you attach a validator decides what it sees:
- On a
FormControl, the validator receives that control and checks its own value. - On a
FormGroup, the validator receives the group and can read every child control. Its error appears on the group, not on a child.
Attaching to a control
Pass validators in the validators option of the FormControl constructor. The array can mix built-in and custom validators. This is the validator from the previous chapter:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export const noWhitespaceValidator: ValidatorFn = (
control: AbstractControl,
): ValidationErrors | null => {
const value = control.value;
if (typeof value !== 'string' || value.length === 0) {
return null;
}
return value.trim().length === 0 ? { whitespace: true } : null;
};Attach it next to Validators.required:
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
export const form = new FormGroup({
name: new FormControl('', {
nonNullable: true,
validators: [Validators.required, noWhitespaceValidator],
}),
});nonNullable: true makes reset() return the control to '' instead of null, which keeps the value type as string.
How errors are merged
Angular runs every validator in the array and merges the returned objects into one. If both validators above fail, errors holds both keys. If all return null, errors is null and the control is VALID.
An empty string illustrates this. Validators.required fails and returns { required: true }. noWhitespaceValidator returns null for an empty string, so only one key appears. The whitespace validator skips empty values on purpose, so required stays the single owner of the "empty" case.
Attaching to a group
A group-level validator is attached through the second argument of the FormGroup constructor. It receives the group as its AbstractControl:
import { AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
export const passwordsMatchValidator: ValidatorFn = (
group: AbstractControl,
): ValidationErrors | null => {
const password = group.get('password')?.value;
const confirm = group.get('confirm')?.value;
return password === confirm ? null : { passwordsMismatch: true };
};
export const signUp = new FormGroup(
{
password: new FormControl(''),
confirm: new FormControl(''),
},
{ validators: passwordsMatchValidator },
);The error passwordsMismatch lives on signUp.errors. Neither child control becomes invalid because of it. The group itself is invalid if any child is invalid or if its own validators return errors.
Attaching after construction
Sometimes you need to change validators at runtime, for example when a field becomes required only after the user ticks a checkbox. Use these methods:
setValidators(validators)replaces the whole list.addValidators(validators)appends to it.removeValidators(validators)removes specific ones by reference.clearValidators()removes all of them.
These methods change the list but do not re-run validation. Call updateValueAndValidity() afterward:
import { FormControl, Validators } from '@angular/forms';
const phone = new FormControl('', { nonNullable: true });
phone.addValidators(Validators.required);
phone.updateValueAndValidity();
console.log(phone.status); // INVALID
phone.removeValidators(Validators.required);
phone.updateValueAndValidity();
console.log(phone.status); // VALIDremoveValidators compares by reference. Pass the same function you added. A validator created inline, or a new factory call, will not match and will stay attached.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Status does not change after `addValidators` | Validation was not re-run | Call `updateValueAndValidity()` |
| `removeValidators` has no effect | A different function reference was passed | Keep the validator in a variable and reuse it |
| Group error never shows on a field | The error is on the group, not the child | Read it from the group |
| Validator called with `null` value | Control is empty or reset | Return `null` for empty values and let `required` handle them |
Exercise
Exercise
A form has a FormGroup with start and end date controls. You attach a validator to the FormGroup that returns { rangeInvalid: true } when end is before start. Which object holds the rangeInvalid error, and is the end control itself invalid because of it?
Show answer
The error is on the group, so form.errors contains rangeInvalid, and form.hasError('rangeInvalid') is true. The end control is not invalid because of it: its own errors stay null unless one of its own validators fails. The group is invalid, though.
Exercise
You call control.addValidators(Validators.required) on an empty control, but control.valid is still true. What is missing, and why?
Show answer
You must call control.updateValueAndValidity(). Adding a validator changes only the validator list. Angular does not re-run validation until the value changes or you request it.