Sub topic 12
Writing Custom Validators
This chapter assumes you know how to create a FormControl, attach built-in validators such as Validators.required, and read hasError() in a template. Built-in validators cover common rules. Most real forms also have rules specific to the domain, such as "no blank names" or "no reserved words." For those rules you write your own validator.
The ValidatorFn contract
A synchronous validator is a plain function of type ValidatorFn. It takes an AbstractControl and returns either:
nullwhen the value is valid, or- a
ValidationErrorsobject, which is a map of error keys to details, when the value is invalid.
Angular calls the function every time the control's value changes. It then merges the returned object into control.errors.
A simple validator and a validator factory
Some validators need no configuration, so you can export them as constants. Other validators need parameters. For those, write a factory: a function that takes the configuration and returns a ValidatorFn.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export const noWhitespace: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (typeof value !== 'string' || value.length === 0) {
return null; // leave empty values to Validators.required
}
return value.trim().length === 0 ? { whitespace: true } : null;
};
export function forbiddenWords(words: string[]): ValidatorFn {
const banned = words.map((w) => w.toLowerCase());
return (control: AbstractControl): ValidationErrors | null => {
const value = String(control.value ?? '').toLowerCase();
const found = banned.find((w) => value.includes(w));
return found ? { forbiddenWord: { word: found } } : null;
};
}You attach custom validators the same way as built-in ones. The error details you return are available in the template through getError():
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { forbiddenWords, noWhitespace } from './validators';
@Component({
selector: 'app-username',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<input [formControl]="username" />
@if (username.hasError('whitespace')) {
<p>Name cannot be only spaces.</p>
}
@if (username.getError('forbiddenWord'); as err) {
<p>"{{ err.word }}" is not allowed.</p>
}
`,
})
export class UsernameComponent {
username = new FormControl('', {
nonNullable: true,
validators: [Validators.required, noWhitespace, forbiddenWords(['admin', 'root'])],
});
}Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Returning `{}` or `false` for a valid value | Angular treats any non-null return as an error, so the control stays invalid | Return `null` |
| Rejecting empty values | You get duplicate errors alongside `required` | Return `null` for empty input |
| Passing `forbiddenWords` without calling it | The factory itself is treated as the validator, so validation breaks | Call it: `forbiddenWords([...])` |
| Calling `setValue` inside a validator | Validation runs again, which can loop forever | Keep validators pure |
| Making an HTTP call | A sync validator cannot wait for a response | Use an async validator (covered later) |
Exercise
Write a validator factory maxWords(limit: number) that returns { maxWords: { limit, actual } } when a string has more than limit words and null otherwise. Empty values should pass.
Show answer
export function maxWords(limit: number): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { const text = String(control.value ?? '').trim(); if (!text) { return null; } const actual = text.split(/\s+/).length; return actual > limit ? { maxWords: { limit, actual } } : null; }; }
Exercise
A control is configured with validators: [noWhitespace] and the user types three spaces. What does control.errors contain, and what is control.status?
Show answer
control.errors is { whitespace: true } and control.status is 'INVALID'.