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 form around it. This chapter covers that model. Later chapters build on it.
Prerequisites
This chapter assumes you have the following:
- TypeScript basics: functions, types and generics.
- Angular components and templates.
- Basic familiarity with reactive forms (
FormControlandFormGroup). - Basic RxJS Observables, needed only for the async part.
Validation belongs to the control
In Angular, every form control owns its validation. A control is a FormControl, a FormGroup or a FormArray. Each one has a list of synchronous validators and a list of asynchronous validators. A validator is a function that receives the control and returns either an error object or null.
Angular runs the validators automatically. It does so when the control is created and again every time its value changes. After each run, the control updates three properties:
statusis one ofVALID,INVALID,PENDINGorDISABLED.errorsis the merged error object, ornullwhen no validator failed.valid,invalidandpendingare boolean shortcuts forstatus.
The following example uses built-in validators, and custom validators behave the same way:
import { FormControl, Validators } from '@angular/forms';
const name = new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
});
console.log(name.status); // INVALID
console.log(name.errors); // { required: true }
name.setValue('ab');
console.log(name.errors); // { minlength: { requiredLength: 3, actualLength: 2 } }
name.setValue('abc');
console.log(name.status); // VALID
console.log(name.errors); // nullEach key in errors is the name of a failed rule. The value is either true or an object with details. Templates and code read errors by these keys, so choose key names with care.
The '' case shows that validators are independent. Validators.minLength returns null for an empty value, so only required reports an error. Angular merges the results of all failing validators into one object.
The order of a validation run
Angular follows a fixed order on every value change:
- It runs all synchronous validators and merges their errors.
- If any synchronous validator failed, the status becomes
INVALID. Async validators are skipped. - If all synchronous validators passed and the control has async validators, the status becomes
PENDING. Angular then subscribes to each async validator. - When the async validators finish, the status becomes
VALIDorINVALID. - The new status is passed up to the parent group.
This order matters for design. Cheap checks belong in synchronous validators, because they stop expensive checks, such as an HTTP call, from running on obviously bad input.
Validity flows upward
A group is valid only if all of its enabled children are valid. When a child's status changes, the parent recomputes its own status.
import { FormControl, FormGroup, Validators } from '@angular/forms';
const form = new FormGroup({
name: new FormControl('', {
nonNullable: true,
validators: [Validators.required],
}),
email: new FormControl('', {
nonNullable: true,
validators: [Validators.email],
}),
});
console.log(form.valid); // false, because name is empty
form.controls.name.setValue('Ada');
console.log(form.valid); // true, because an empty email passes Validators.emailA group can also have its own validators. Their errors appear in form.errors, not in a child's errors. This is how cross-field rules work, and a later chapter covers it.
Disabled controls are a special case. A disabled control has the status DISABLED, runs no validators and is ignored when the group computes its validity.
Forms and the DOM
The validation model is the same in reactive and template-driven forms. Directives such as formControl or ngModel connect an <input> to a control. They also collect validators from the template. For example, a required attribute adds Validators.required to the control. Because of this shared model, one validator function can serve both styles of form. The chapter on template-driven forms shows how.
Common mistakes
- Reading
errorswithout a null check. The value isnullwhen the control is valid, so usecontrol.errors?.['required']orcontrol.hasError('required'). - Treating
PENDINGas invalid. A control with a running async validator has neithervalidnorinvalidset to true. - Expecting a validator to run when a different control changes. A control's validators rerun only when its own value changes. A rule that depends on a sibling must live on the parent group.
Exercise
A control has Validators.required and an async validator that calls a server. The user clears the field, leaving it empty. Does the server get called, and what is the control's status?
Show answer
The server is not called. Validators.required fails, so the control is INVALID with errors { required: true }. Async validators run only when all synchronous validators pass.
Exercise
A FormGroup has two children. One is VALID and the other is DISABLED. What is the group's status?
Show answer
The group is VALID. A disabled child is excluded from the group's validity calculation, so only the enabled valid child counts.