Sub topic 9
Write custom validators
Built-in validators such as required(), email() and minLength() cover common rules. Sooner or later a form needs a rule that only your application has, such as "usernames cannot contain spaces" or "the end date must come after the start date". This chapter shows how to write those rules with validate(), how to package them for reuse, and what mistakes to avoid.
This chapter assumes you can create a form with form() and a signal model, you can bind fields with [field], and you can read field state such as invalid() and errors(). It also assumes you know signal() and computed(). Signal Forms is experimental in Angular 21, so names and signatures can change in later releases.
What a validator is
A custom validator is a function that looks at a field and answers one question: is the value acceptable? You register it inside the schema function passed to form(), using validate().
validate() takes two arguments:
- The path of the field to check, such as
path.username. - A validator function that receives a context object and returns either
null(the value is valid) or an error object.
An error object has a kind, which is a short machine-readable name, and usually a message for people. The kind is what your template or code uses to tell one failure from another. The message is what you show.
import { signal } from '@angular/core';
import { form, required, validate } from '@angular/forms/signals';
const model = signal({ username: '' });
const accountForm = form(model, (path) => {
required(path.username, { message: 'Username is required' });
validate(path.username, ({ value }) =>
value().includes(' ')
? { kind: 'whitespace', message: 'Usernames cannot contain spaces' }
: null
);
});Here value is a signal that holds the current value of the field, so you call it as value(). The validator returns null for a good value and an error object for a bad one.
How validators run
Signal Forms validators are reactive. When the validator reads a signal, such as value(), the form records the dependency. When that signal changes, the validator runs again and the field's errors() and valid() update. You do not subscribe, trigger, or call updateValueAndValidity() as you would in Reactive Forms.
Mermaid is required to be inside a "diagram mermaid" fence, so here is the diagram in the correct form.
This also explains one rule: a validator should be a pure function of signals. Do not write to signals, call the server, or depend on values that are not signals. If you read a plain variable, the form cannot know when it changes.
The validator context
The function you pass to validate() receives a context object. Two members cover most needs:
| Member | What it gives you |
|---|---|
| `value` | A signal with the current value of the field being validated. |
| `valueOf` | A function that reads the value of another field when you pass it that field's path. |
valueOf(path.other) is what makes cross-field rules possible. The next chapter treats those in detail, but one short example shows the idea:
import { signal } from '@angular/core';
import { form, validate } from '@angular/forms/signals';
const model = signal({ start: 1, end: 5 });
const rangeForm = form(model, (path) => {
validate(path.end, ({ value, valueOf }) =>
value() >= valueOf(path.start)
? null
: { kind: 'range', message: 'End must not be before start' }
);
});Because valueOf(path.start) reads a signal inside the validator, the end field is re-validated whenever start changes, even though the user never touched end.
Leave empty values to required()
A common mistake is to make a custom validator reject empty input. Suppose you check that a username has at least one letter. An empty string has no letters, so the validator would add a second error on top of required(), and the user sees two messages for one problem.
Give each rule one job. Let required() handle emptiness, and have your validator return null for an empty value:
import { signal } from '@angular/core';
import { form, required, validate } from '@angular/forms/signals';
const model = signal({ username: '' });
const usernameForm = form(model, (path) => {
required(path.username, { message: 'Username is required' });
validate(path.username, ({ value }) => {
const current = value();
if (current === '') {
return null; // required() reports this case
}
return /^[a-z][a-z0-9_]*$/.test(current)
? null
: {
kind: 'username-format',
message: 'Start with a lowercase letter, then use letters, digits, or _',
};
});
});Package a validator as a reusable function
If two forms need the same rule, do not copy the validate() call. Wrap it in a function that takes a field path. The built-in validators work the same way: required(path.x) is a function that takes a path and calls the validation machinery for you.
import { validate, SchemaPath } from '@angular/forms/signals';
export function noWhitespace(path: SchemaPath<string>, message = 'Spaces are not allowed') {
validate(path, ({ value }) =>
/\s/.test(value()) ? { kind: 'whitespace', message } : null
);
}SchemaPath<string> says the helper accepts the path of a string field. If someone passes a number field, TypeScript reports an error at compile time. Use it inside any schema function:
import { signal } from '@angular/core';
import { form, required } from '@angular/forms/signals';
import { noWhitespace } from './no-whitespace';
const model = signal({ username: '', nickname: '' });
const profileForm = form(model, (path) => {
required(path.username);
noWhitespace(path.username);
noWhitespace(path.nickname, 'Nicknames cannot contain spaces');
});Add parameters when the rule needs configuration. A factory-style helper such as maxWords(path, limit) reads naturally next to minLength(path.password, 8).
Show custom errors in a template
Custom errors appear in the same errors() signal as built-in ones. Each error carries the kind and message you returned, so the display code from the error-display chapter works unchanged. You can also branch on kind when one error needs special treatment:
import { Component, signal } from '@angular/core';
import { form, Field, required, validate } from '@angular/forms/signals';
@Component({
selector: 'app-username',
imports: [Field],
template: `
<label>Username <input [field]="userForm.username" /></label>
@if (userForm.username().touched() && userForm.username().invalid()) {
@for (error of userForm.username().errors(); track error.kind) {
<p class="error">{{ error.message }}</p>
}
}
`,
})
export class UsernameComponent {
private readonly model = signal({ username: '' });
protected readonly userForm = form(this.model, (path) => {
required(path.username, { message: 'Username is required' });
validate(path.username, ({ value }) =>
value().includes(' ')
? { kind: 'whitespace', message: 'Usernames cannot contain spaces' }
: null
);
});
}The track error.kind expression requires each error on a field to have a different kind. If two validators on the same field return the same kind, Angular warns about duplicate keys. Give each rule its own name.
Common errors
- Returning
falseortrue. The validator must returnnullor an error object. A boolean is not an error object and will not give you the behavior you expect. - Forgetting the
kind. Without a distinctkind, errors are hard to tell apart in templates and in tests. - Reading values outside signals. Use
value()andvalueOf(). Copying a value into a local variable outside the validator freezes it. - Doing slow or remote work.
validate()is for synchronous checks. A username-availability check against a server belongs in asynchronous validation, covered in a later chapter. - Duplicating
required(). As shown above, returnnullfor empty input and letrequired()speak. - Relying on exact names. The API is experimental. Keep custom validators in a small number of helper files so a rename in a later Angular release touches few places.
Summary
A custom validator is a function passed to validate() with a field path. It returns null when the value is valid and an error object with a kind and message when it is not. It reads values through signals, so it re-runs by itself. Wrap repeated rules in helper functions typed with SchemaPath, return null for empty values, and give every rule a unique kind.
Exercise
Write a reusable helper maxWords(path, limit) for a string field. It should return an error with kind max-words and a message when the value has more than limit words, and null otherwise. What should it return for an empty string, and why?
Show answer
Split the trimmed value on whitespace and count the non-empty parts. For example: export function maxWords(path: SchemaPath<string>, limit: number) { validate(path, ({ value }) => { const text = value().trim(); const count = text === '' ? 0 : text.split(/\s+/).length; return count > limit ? { kind: 'max-words', message: Use at most ${limit} words } : null; }); }. An empty string has zero words, so the validator returns null. Emptiness is the job of required(), and returning null keeps the user from seeing two messages for one problem.
Exercise
A validator on end reads valueOf(path.start). The user changes only start. Does the end field's errors() update, and why?
Show answer
Yes. valueOf(path.start) reads the start signal inside the validator, so the form records it as a dependency of the end validator. When start changes, the validator runs again and errors() on end updates without any manual call.