Sub topic 3
Returning errors: ValidationErrors and null
This chapter assumes you know TypeScript functions and types, Angular reactive forms (FormControl, FormGroup), and basic RxJS. It covers one rule: what a validator returns, and how Angular uses that value.
The two possible results
A synchronous validator returns one of two things:
nullwhen the value is valid.- A
ValidationErrorsobject when the value is invalid.
ValidationErrors is an Angular type for a plain object. Each key is an error name, and each value is whatever you want to attach to that error. The value is often true, but it can be any data.
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;
};This validator returns { whitespace: true } for a value like " ". It returns null in every other case, including the empty string.
Why null means valid
Angular does not look for a valid: true flag. It checks whether your function returned null. If it did, the validator adds nothing to the control's errors. If every validator returns null, the control's errors property is null and its status becomes VALID.
Returning {} or { whitespace: false } does not mean valid. Any non-null object marks the control INVALID. Never write { whitespace: false } to say "no problem here". Return null.
flowchart TDIgnore the line above. The real diagram follows.
Leave empty values to required
Notice that noWhitespaceValidator returns null for an empty string. This is a convention. A validator should check one rule only. Emptiness belongs to Validators.required. If every custom validator also rejected empty values, an optional field could never be left blank.
Carrying details in the error value
The error value can hold data that the template displays. A validator factory like this one reports which value was rejected:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function forbiddenNameValidator(forbidden: string[]): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (typeof value !== 'string') {
return null;
}
return forbidden.includes(value.toLowerCase())
? { forbiddenName: { value } }
: null;
};
}When the user types Admin, the control's errors becomes { forbiddenName: { value: 'Admin' } }. A template can read it with control.getError('forbiddenName')?.value. Factories are covered in detail in a later chapter. Here the point is that the error value is yours to design.
How errors from several validators merge
You can attach several validators to one control. Angular runs all of them and merges every non-null result into a single object. Neither a failing validator nor Validators.required stops the others from running.
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],
}),
});An empty name gives { required: true }. A name of three spaces passes required, so the errors are { whitespace: true }. If two validators used the same key, the later one would overwrite the earlier one. Give each validator a distinct key.
Reading errors from a control
Three members read the result:
| Member | Returns |
|---|---|
| `control.errors` | The merged `ValidationErrors` object, or `null` |
| `control.hasError('key')` | `true` if that key is present |
| `control.getError('key')` | The value stored under that key, or `null` |
@if (form.controls.name.hasError('required')) {
<p>Name is required.</p>
}
@if (form.controls.name.hasError('whitespace')) {
<p>Name cannot be only whitespace.</p>
}The @if syntax needs Angular 17 or later. Showing errors only after the user interacts is the topic of a later chapter.
Common mistakes
- Returning
falseorundefinedinstead ofnull. The typeValidationErrors | nullrejectsfalse.undefinedis notnull, so a strict check can treat the control as invalid. - Returning
{ key: false }to mean valid. Any object makes the control invalid. - Throwing an error for bad input. A thrown exception breaks the form instead of reporting a validation failure. Return an error object.
- Assuming the value is a string. A control's value can be
nullor a number, so check its type first, as the examples above do.
Exercise
A validator returns { tooShort: false } for a value that is long enough. What is the control's status, and what should the validator return instead?
Show answer
The control is INVALID, because any non-null object counts as an error. The validator should return null when the value is long enough, and { tooShort: true } (or an object with details) only when it is too short.
Exercise
A control has Validators.required and noWhitespaceValidator. The user enters " ". What does control.errors contain, and why?
Show answer
{ whitespace: true }. The string is not empty, so required returns null. noWhitespaceValidator finds the trimmed value empty and returns its error. Angular merges only the non-null results.