Sub topic 1
How Angular forms run validation
Before you write a custom validator, you need to know when Angular calls it, what it does with the result, and how that result reaches the template. This chapter covers that machinery. Later chapters build the validators themselves.
Prerequisites
This chapter assumes you know:
- TypeScript basics: functions, types, and generics.
- Angular components and templates.
- The basics of reactive forms: creating a
FormControland aFormGroup. - What an RxJS
Observableis and how to subscribe to one.
The examples use Angular 17 or later with standalone components. Everything about validation timing also applies to earlier versions.
The building blocks
Angular's reactive forms are built from three classes that share one base class, AbstractControl.
FormControlholds a single value, such as the text in an input.FormGroupholds a set of named child controls.FormArrayholds an ordered list of child controls.
Every AbstractControl has the same validation-related properties:
| Property | Meaning |
|---|---|
| `value` | The current value. For a group, an object built from its children. |
| `status` | One of `VALID`, `INVALID`, `PENDING`, or `DISABLED`. |
| `errors` | A `ValidationErrors` object, or `null` when there are no errors. |
| `valid`, `invalid`, `pending`, `disabled` | Boolean shortcuts for `status`. |
| `dirty`, `touched` | Whether the user has changed the value or visited the field. |
A validator is a function that takes a control and returns either null (no problem) or an object describing what is wrong. You attach validators when you create a control or later with setValidators. Angular calls them and stores the outcome in errors and status. Your validator never sets those properties itself.
What triggers validation
Angular validates a control when something calls its updateValueAndValidity() method. You rarely call it directly, because these operations call it for you:
- Creating a control runs validation once, so a control that starts invalid has
statusofINVALIDimmediately. setValueandpatchValuerun it.- User input in a bound element runs it, through the value accessor that connects the DOM to the control.
enable()anddisable()run it.reset()runs it.
The following example shows the first few triggers in action.
import { FormControl, Validators } from '@angular/forms';
const control = new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
});
console.log(control.status); // INVALID
console.log(control.errors); // { required: true }
control.setValue('ab');
console.log(control.errors);
// { minlength: { requiredLength: 3, actualLength: 2 } }
control.setValue('abc');
console.log(control.status); // VALID
console.log(control.errors); // nullWith an empty string, only required reports an error. The built-in minLength deliberately returns null for empty values so that "is it filled in?" and "is it long enough?" stay separate questions. Your own validators should follow the same convention, which later chapters return to.
The validation pipeline
When updateValueAndValidity() runs on a control, it follows these steps.
- If the control is disabled, it sets
statustoDISABLEDanderrorstonull. No validator runs. - Otherwise it runs all synchronous validators and merges their results into
errors. - If the synchronous result is empty, it sets
statustoVALID. Otherwise it setsstatustoINVALID. - If
statusisVALIDand the control has async validators, it setsstatustoPENDINGand subscribes to them. - When the async validators finish, it stores their errors and moves
statustoVALIDorINVALID. - It emits
valueChangesandstatusChanges, then repeats the update on its parent.
Two details in this pipeline matter when you design validators.
Synchronous validators all run
Angular does not stop at the first failing synchronous validator. It calls every validator in the array, in order, and merges the returned objects into one. This is what lets the template show both "required" and "pattern" errors at once if both apply.
import { AbstractControl, FormControl, ValidationErrors, Validators } from '@angular/forms';
const alwaysFails = (_: AbstractControl): ValidationErrors | null => ({ first: true });
const alsoFails = (_: AbstractControl): ValidationErrors | null => ({ second: true });
const control = new FormControl('x', [alwaysFails, alsoFails, Validators.minLength(3)]);
console.log(control.errors);
// { first: true, second: true, minlength: { requiredLength: 3, actualLength: 1 } }If two validators return the same key, the later one overwrites the earlier one in the merged object. Choose distinct error keys.
Async validators wait for sync validators
Async validators run only when every synchronous validator has passed. If a username is empty and required fails, Angular does not call your server-check validator. This saves requests, and it means an async validator can assume the synchronous rules already hold.
Status values
A control is always in exactly one of four states.
| Status | When it applies | `errors` |
|---|---|---|
| `VALID` | All validators passed. | `null` |
| `INVALID` | At least one validator returned an error. | An object |
| `PENDING` | Sync validators passed and async validators have not finished. | Previous value until the async result arrives |
| `DISABLED` | The control is disabled. | `null` |
PENDING is the state beginners miss most often. A control that is pending is neither valid nor invalid, so control.valid and control.invalid are both false. A submit button bound to [disabled]="form.invalid" is therefore enabled while an async check is running. Use form.valid for the submit condition instead, or check form.pending explicitly.
How groups aggregate their children
A FormGroup has its own errors and status, and it computes them from two sources: validators attached to the group itself, and the status of its children.
Angular applies these rules in order:
- If every child is disabled, the group is
DISABLED. - If the group's own validators returned errors, the group is
INVALID. - If the group has a pending async validator, or any child is
PENDING, the group isPENDING. - If any child is
INVALID, the group isINVALID. - Otherwise the group is
VALID.
The important consequence is that group.errors contains only errors from validators on the group. A child's errors stay on the child. When a child is invalid, group.status is INVALID but group.errors can still be null.
import { FormControl, FormGroup, Validators } from '@angular/forms';
const form = new FormGroup({
email: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
age: new FormControl(30, { nonNullable: true }),
});
console.log(form.status); // INVALID
console.log(form.errors); // null: the group has no validators of its own
console.log(form.controls.email.errors); // { required: true }
console.log(form.get('email')?.hasError('required')); // trueRule 3 comes before rule 4, so a group with one pending child and one invalid child reports PENDING. It becomes INVALID once the async check finishes. Rule 2 comes first, so a group-level error overrides everything else. Cross-field validators, covered in a later chapter, depend on this behavior.
Disabled children are skipped when the group builds its value (use getRawValue() to include them) and when it aggregates status. A disabled child never makes its group invalid.
Changing validators at runtime
You can replace a control's validators after creation with setValidators, addValidators, removeValidators, clearValidators, and the matching ...AsyncValidators methods. These methods only change the list. They do not re-run validation, so the control keeps its old errors until something triggers an update.
import { FormControl, Validators } from '@angular/forms';
const phone = new FormControl('');
console.log(phone.valid); // true
phone.setValidators([Validators.required]);
console.log(phone.valid); // still true: nothing has re-run validation
phone.updateValueAndValidity();
console.log(phone.valid); // falseWhen a rule in one field depends on the value of another, you also need to re-validate the dependent control yourself. Angular re-validates a parent group when a child changes, but it does not re-validate a sibling.
Events and subscriptions
Each update emits two observables on the control.
valueChangesemits the new value.statusChangesemits the new status string.
Order matters: validation finishes before either event fires, so a valueChanges subscriber that reads control.errors sees the result for the new value. Because async validation completes later, statusChanges emits PENDING first and then VALID or INVALID after the async result.
import { FormControl } from '@angular/forms';
import { map, timer } from 'rxjs';
const control = new FormControl('alice', {
asyncValidators: [
(c) => timer(100).pipe(map(() => (c.value === 'alice' ? { taken: true } : null))),
],
});
control.statusChanges.subscribe((status) => console.log('status:', status));
control.setValue('bob');
// status: PENDING
// status: VALID (about 100 ms later)Most methods accept { emitEvent: false } to suppress these events, and { onlySelf: true } to skip updating the parent. Both change what other code sees, so use them deliberately.
Where `updateOn` fits
By default a control validates on every input event. The updateOn option changes when the control's value updates, and validation follows the value update. The options are 'change' (the default), 'blur', and 'submit'.
import { FormControl, Validators } from '@angular/forms';
const email = new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.email],
updateOn: 'blur',
});With updateOn: 'blur', the control's value and errors change only when the user leaves the field. Calling setValue in code still validates immediately. A later chapter covers this together with pending state and revalidation.
Reading validation state in a template
Angular exposes the state described above to templates. The two properties you will use most are invalid and hasError('key'). To avoid showing errors before a user has done anything, combine them with touched or dirty.
<input id="email" type="email" [formControl]="form.controls.email" />
@if (form.controls.email.invalid && form.controls.email.touched) {
@if (form.controls.email.hasError('required')) {
<p>Email is required.</p>
}
}hasError('required') checks whether the key exists in errors. It does not read the error's value. To display details, such as the required length from minlength, read control.getError('minlength'). A later chapter covers this in full.
Common mistakes
- Reading
errorsand expecting a boolean.errorsisnullor an object. Checkcontrol.validfor the yes/no answer. - Treating
PENDINGas invalid or valid. It is neither. Handle it explicitly in submit logic. - Expecting
group.errorsto list child errors. Those stay on the children. - Changing validators without re-validating. Call
updateValueAndValidity(). - Expecting async validators to run on invalid input. They wait for the synchronous validators to pass.
- Using the same error key in two validators. The later one overwrites the earlier one.
Summary
Validation is a pipeline that runs when updateValueAndValidity() is called. Synchronous validators all run and their errors merge. Async validators run only if the synchronous ones pass, and they put the control in PENDING. A group derives its status from its own validators and its children, but only its own validators populate group.errors. Changing validators does not re-run them. With this model, the contract for a custom validator is simple: take a control, return null or an error object, and let Angular do the rest.
Exercise
A form has a control username with validators [Validators.required] and an async validator that checks a server. The user has typed "bob" and the async request is still in flight. What are username.status, username.valid, and username.invalid, and why can a submit button bound to [disabled]="form.invalid" be a bug here?
Show answer
The status is PENDING. Both valid and invalid are false, because a pending control is neither. Since form.invalid is false, the submit button is enabled while the async check is still running, so the user can submit before the check finishes. Bind the button to [disabled]="!form.valid" (or also check form.pending) instead.
Exercise
You call control.setValidators([Validators.required]) on a control whose value is an empty string, then read control.valid and get true. Why, and what is the fix?
Show answer
setValidators only replaces the validator list and does not re-run validation, so the old result (VALID) is still stored. Call control.updateValueAndValidity() after setValidators, and valid will become false.