Sub topic 3
Returning errors: ValidationErrors and null
This chapter covers what a validator returns and how Angular stores, merges and exposes that result. It assumes you can write a basic FormControl and FormGroup, read TypeScript types, and have seen the validator function signature from the previous chapter. The return value is small, but most validator bugs come from getting it wrong: wrong keys, wrong types for the details, or errors on the wrong object.
The two possible results
A synchronous validator returns one of two things:
nullmeans the value is valid.- A
ValidationErrorsobject means the value is invalid.
ValidationErrors is declared in @angular/forms as a map from a string key to any value:
type ValidationErrors = { [key: string]: any };Each key names one kind of failure, such as required, minlength or whitespace. The value is either true or an object with details about the failure. Angular does not look inside the value. It only checks whether the result is null or an object.
A control is INVALID whenever its errors property is not null. You never set the status yourself. Angular runs the validators each time the value changes, stores the result in control.errors, and derives the status from it.
import { FormControl, Validators } from '@angular/forms';
const empty = new FormControl('', Validators.required);
console.log(empty.status); // 'INVALID'
console.log(empty.errors); // { required: true }
const filled = new FormControl('Ada', Validators.required);
console.log(filled.status); // 'VALID'
console.log(filled.errors); // nullThe result of a valid control is null, not an empty object and not false. Keep to that rule in your own validators.
Choosing the error key
The key is the public name of your error. Templates, tests and other validators refer to it, so treat it like part of an API.
- Use a short, descriptive name in lower camel case, such as
whitespaceorpasswordsMismatch. - Do not reuse a built-in key such as
required,minlength,maxlength,min,max,emailorpatternfor a different meaning. A template that checkshasError('required')would then show the wrong message. - Use one key per distinct failure. If a field can fail in two unrelated ways, return two different keys, or write two validators.
The built-in validators set a useful example. Validators.required returns { required: true }. Validators.minLength(5) returns { minlength: { requiredLength: 5, actualLength: 3 } }. The first has no useful detail, so its value is true. The second has details that a message can show, so its value is an object.
Putting details in the error value
Return true when the key alone says everything. Return an object when the template could use extra information, such as the limit that was exceeded or the value that was rejected.
The validator below requires at least two words. Its error value reports how many words are required and how many were found.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export interface TwoWordsError {
required: number;
actual: number;
}
export const twoWordsValidator: ValidatorFn = (
control: AbstractControl,
): ValidationErrors | null => {
const value = control.value;
if (typeof value !== 'string' || value.trim().length === 0) {
return null;
}
const actual = value.trim().split(/\s+/).length;
const required = 2;
if (actual >= required) {
return null;
}
const detail: TwoWordsError = { required, actual };
return { twoWords: detail };
};Two choices in this code are worth copying.
First, the validator returns null for empty input. Whether a field may be empty is the job of Validators.required. If every validator also complained about empty values, a blank field would show several errors at once, and optional fields could never be left blank.
Second, the validator checks typeof value !== 'string' before using string methods. A control's value can be null or a number, for example after a reset() on a control that is not nonNullable. Calling value.trim() on null would throw inside Angular's change detection.
How the result becomes control.errors
When a control has several validators, Angular runs all of them and merges the results into one object. It does not stop at the first failure.
import { FormControl, Validators } from '@angular/forms';
const code = new FormControl('ab', [
Validators.minLength(3),
Validators.pattern('[0-9]+'),
]);
console.log(Object.keys(code.errors ?? {})); // ['minlength', 'pattern']Both validators failed, so errors contains both keys. This is why each validator should use its own key. If two validators return the same key, the one that runs later replaces the earlier value, because the objects are merged with a spread. Validators run in the order of the array.
Validators that return null add nothing. If every validator returns null, the merged result is null and the control is valid.
A related edge case is returning an empty object. If a control has a single validator, the empty object is stored as it is, so errors is {} and the control is INVALID with no failing key. When several validators are combined, Angular drops an empty merged result and treats it as valid. The same return value gives different outcomes depending on how the validator is attached. Avoid the issue by returning null for valid input.
The flow for one control looks like this:
Reading errors in code and templates
A control exposes its errors in three ways:
| Member | Returns | Use |
|---|---|---|
| `control.errors` | The merged object, or `null` | Inspecting everything that failed |
| `control.hasError('key')` | `true` or `false` | Deciding whether to show a message |
| `control.getError('key')` | The value stored under the key, or `null` | Reading the details |
hasError and getError also accept a path as a second argument. Called on a group, group.hasError('passwordsMismatch') checks the group's own errors, and group.hasError('required', 'email') checks the email child.
Here is a component that shows the details from twoWordsValidator. It uses getError rather than errors.twoWords. With the TypeScript option noPropertyAccessFromIndexSignature, dotted access to an index-signature property is a compile error, and getError avoids the problem.
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { TwoWordsError, twoWordsValidator } from './two-words.validator';
@Component({
selector: 'app-title-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<label for="title">Title</label>
<input id="title" type="text" [formControl]="form.controls.title" />
@if (form.controls.title.invalid && (form.controls.title.dirty || form.controls.title.touched)) {
@if (form.controls.title.hasError('required')) {
<p>Title is required.</p>
}
@if (twoWordsError(); as detail) {
<p>Use at least {{ detail.required }} words. You wrote {{ detail.actual }}.</p>
}
}
`,
})
export class TitleFormComponent {
readonly form = new FormGroup({
title: new FormControl('', {
nonNullable: true,
validators: [Validators.required, twoWordsValidator],
}),
});
twoWordsError(): TwoWordsError | null {
return this.form.controls.title.getError('twoWords');
}
}The template waits for dirty or touched before showing messages, so the user does not see errors on a page they have not touched yet. The getError result is typed as any, so the method's return type annotation is what gives the template its type safety.
Errors on groups versus errors on controls
Where a validator is attached decides where its error appears. A validator attached to a control writes to that control's errors. A validator attached to a group writes to the group's errors, and the child controls are not touched.
import { FormControl, FormGroup } from '@angular/forms';
import { passwordsMatchValidator } from './passwords-match.validator';
const form = new FormGroup(
{
password: new FormControl('secret1', { nonNullable: true }),
confirm: new FormControl('secret2', { nonNullable: true }),
},
{ validators: passwordsMatchValidator },
);
console.log(form.errors); // { passwordsMismatch: true }
console.log(form.controls.confirm.errors); // null
console.log(form.invalid); // trueThis explains a common surprise. The confirm input is not marked invalid, so a CSS rule such as input.ng-invalid does not highlight it, while the form as a whole is invalid. Read the error from form.hasError('passwordsMismatch') and decide in the template where to display it. A later chapter covers cross-field validators in full.
A group is INVALID if its own errors is not null or if any child is invalid. Child errors are not copied into the group's errors.
Errors you set by hand
control.setErrors({ server: 'Email already registered' }) writes an error directly. It is useful for showing a message that came back from a server after submit.
Two rules apply:
- The next validation run replaces the object. After the user edits the field, Angular recalculates
errorsfrom the validators, and your manual error disappears. setErrors(null)makes the control valid at that moment, even if a validator would fail. The next run corrects it, so do not use it to bypass validation.
import { FormControl } from '@angular/forms';
const email = new FormControl('[email protected]', { nonNullable: true });
email.setErrors({ server: 'Email already registered' });
console.log(email.invalid); // true
email.setValue('[email protected]');
console.log(email.invalid); // falseMistakes to avoid
- Returning
falsefor valid. The valuefalseis notnull. In TypeScript it is a type error forValidatorFn, but in untyped code it is easy to write, and a falsy non-null result gives inconsistent behavior. Returnnull. - Returning
{ whitespace: false }for valid. The object is notnull, so the control is invalid even though the value isfalse. Returnnulland leave the key out. - Mutating the control or the returned object between calls. A validator should read the control and build a new object each time. Reusing one shared error object across calls invites bugs when a consumer changes it.
- Throwing for bad input. An exception in a validator breaks the whole form update. Return
nullor an error object instead. - Forgetting that
control.valuecan benull, a number or an object. Narrow the type before use.
Summary of the contract
- Valid input returns
null. - Invalid input returns an object whose keys name each failure.
- Each value is
trueor a details object that the template can show. - Angular merges results from all validators on the control, and a later validator wins on a duplicate key.
- The status follows
errors:nullis valid, anything else is invalid. - A group validator reports on the group, not on its children.
Exercise
A control has the validators [Validators.required, noWhitespaceValidator], where noWhitespaceValidator returns { whitespace: true } for a value made only of spaces and null otherwise. What are control.errors and control.status when the value is three spaces, and what are they when the value is an empty string?
Show answer
For three spaces, required passes because the string is not empty, and noWhitespaceValidator fails, so errors is { whitespace: true } and status is INVALID. For an empty string, required fails with { required: true }, and noWhitespaceValidator returns null because it ignores empty values, so errors is { required: true } and status is INVALID.
Exercise
A validator is written as (control) => control.value === 'admin' ? { reserved: true } : { reserved: false }. Why does every control that uses it become invalid, and how do you fix it?
Show answer
The function returns an object in both branches, and Angular treats any non-null result as an error, so { reserved: false } still sets errors and makes the control INVALID. Return null in the valid branch: control.value === 'admin' ? { reserved: true } : null.
Exercise
A FormGroup has a group-level validator that returns { passwordsMismatch: true }. The template checks form.controls.confirm.hasError('passwordsMismatch') and never shows the message. Why, and what should the template check instead?
Show answer
A group validator stores its error on the group's own errors, not on any child control, so the confirm control has no such error. Check form.hasError('passwordsMismatch') on the group, or call form.hasError('passwordsMismatch') in the template next to the confirm input.