Sub topic 13
Writing Custom Validators
Built-in validators cover required fields, lengths, patterns, and numeric ranges. Real forms also need domain rules, such as "no blank-only names" or "this field must not contain a reserved word." In Angular you write those rules as validator functions. This chapter covers how to write them, how to pass them parameters, and how to attach and detach them at runtime.
This chapter assumes you already know how to create typed FormControl and FormGroup instances, apply built-in validators, and read errors, touched, and dirty to show messages. Validators that compare two fields and validators that call a server have their own chapters later.
The ValidatorFn Contract
A synchronous validator is a plain function with the type ValidatorFn:
import { AbstractControl, ValidationErrors } from '@angular/forms';
type MyValidatorFn = (control: AbstractControl) => ValidationErrors | null;The contract has three rules:
- The function receives the control being validated. That can be a
FormControl,FormGroup, orFormArray, because they all extendAbstractControl. - It returns
nullwhen the value is valid. - It returns a
ValidationErrorsobject when the value is invalid. That is a map from an error key to any value, for example{ noWhitespace: true }.
Angular runs every validator on a control and merges their error objects into control.errors. If all of them return null, control.errors is null and the status is VALID.
A Simple Validator
This validator rejects values that contain only spaces. Validators.required accepts " " because the string is not empty.
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; // let Validators.required handle empty values
}
return value.trim().length === 0 ? { noWhitespace: true } : null;
};Note the early return null for empty values. This is the convention the built-in validators follow: Validators.email and Validators.minLength treat an empty value as valid. Each validator checks one rule and leaves emptiness to required. Without this convention, an optional field would show errors before the user types anything, and the same empty field would carry two error keys for one problem.
Parameterized Validators with Factories
When a rule needs configuration, write a factory: a function that takes the parameters and returns a ValidatorFn. Validators.minLength(3) works the same way.
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function forbiddenWords(words: string[]): ValidatorFn {
const lowered = words.map((w) => w.toLowerCase());
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
if (typeof value !== 'string' || value === '') {
return null;
}
const text = value.toLowerCase();
const found = lowered.find((w) => text.includes(w));
return found ? { forbiddenWord: { word: found } } : null;
};
}The error value is an object here, not just true. A payload like { word: 'admin' } lets the template build a specific message without repeating the validator's logic. Built-in validators do the same thing: minlength reports { requiredLength, actualLength }.
Attaching Validators and Showing Errors
You attach custom validators exactly like built-in ones, in the validators array:
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { forbiddenWords, noWhitespace } from './validators';
@Component({
selector: 'app-username-field',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<label>
Username
<input [formControl]="username" />
</label>
@if (username.touched && username.errors; as errors) {
@if (errors['required']) {
<p>Username is required.</p>
}
@if (errors['noWhitespace']) {
<p>Username cannot be only spaces.</p>
}
@if (errors['forbiddenWord']; as e) {
<p>"{{ e.word }}" is not allowed in a username.</p>
}
}
`,
})
export class UsernameFieldComponent {
username = new FormControl('', {
nonNullable: true,
validators: [Validators.required, noWhitespace, forbiddenWords(['admin', 'root'])],
});
}Error keys are strings, so TypeScript cannot check them. A typo such as errors['forbiddenWords'] never matches and fails silently. In larger apps, export the key as a constant next to the validator and use it in both places.
Adding and Removing Validators at Runtime
Sometimes a rule applies only in certain conditions. Controls have methods for this:
| Method | Effect | Column | Column |
|---|---|---|---|
| `addValidators(fn \ | fn[])` | Adds to the existing validators | |
| `removeValidators(fn \ | fn[])` | Removes by function reference | |
| `hasValidator(fn)` | Checks by function reference | ||
| `setValidators(fn \ | fn[] \ | null)` | Replaces all validators |
| `clearValidators()` | Removes all validators |
None of these methods re-run validation. You must call updateValueAndValidity() afterwards, or the control keeps its old status until the value next changes.
import { FormControl, Validators } from '@angular/forms';
import { forbiddenWords } from './validators';
const reserved = forbiddenWords(['admin', 'root']);
const username = new FormControl('admin', { nonNullable: true });
console.log(username.valid); // true
username.addValidators(reserved);
console.log(username.valid); // still true: not re-validated yet
username.updateValueAndValidity();
console.log(username.valid); // false
console.log(username.hasValidator(reserved)); // true
console.log(username.hasValidator(forbiddenWords(['admin', 'root']))); // false
username.removeValidators(reserved);
username.updateValueAndValidity();
console.log(username.valid); // true
username.addValidators(Validators.required); // built-ins are stable references
console.log(username.hasValidator(Validators.required)); // trueCommon Mistakes
- Returning
{}orfalsefor valid input. Angular treats any non-null return as an error map. Returnnullfor valid input. - Throwing on unexpected types.
control.valuecan benullafterreset()on a nullable control, or a number on an input withtype="number". Guard with a type check and returnnull. - Side effects inside the validator. Validators run on every value change and during initialization. Keep them pure: no HTTP calls, no writing to other controls, no logging in production code.
- Expensive work in the factory body versus the inner function. Put one-time setup, such as lowercasing the word list or compiling a
RegExp, in the factory, asforbiddenWordsdoes. The inner function runs on every keystroke. - Forgetting the parent. A control's error also makes its parent group
INVALID, so a hidden field with a failing custom validator can block submission. Disable the control or remove the validator when the field is not in use.
Exercise
Write a factory maxWords(limit: number): ValidatorFn that fails when a string contains more than limit whitespace-separated words. It should report how many words were found, and it should leave empty values to Validators.required.
Show answer
export function maxWords(limit: number): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { const value = control.value; if (typeof value !== 'string' || value.trim() === '') { return null; } const count = value.trim().split(/\s+/).length; return count > limit ? { maxWords: { limit, actual: count } } : null; }; } The early null return keeps empty input valid for this rule, and the payload { limit, actual } lets the template show "12 of 10 words".
Exercise
A component calls this.bio.addValidators(maxWords(50)) when a checkbox is ticked and this.bio.removeValidators(maxWords(50)) when it is unticked. After unticking, the error stays. Give two reasons and the fix.
Show answer
First, removeValidators compares by reference, and maxWords(50) creates a new function each time, so nothing is removed. Second, neither method re-runs validation. Fix: store the validator once, for example private bioLimit = maxWords(50);, pass this.bioLimit to both addValidators and removeValidators, and call this.bio.updateValueAndValidity() after each change.