Sub topic 9
Write custom validators
This chapter assumes you can build a form with form(), bind fields with [field], and read field state as signals. It also assumes you have used the built-in validators such as required() and email().
When built-in validators are not enough
Built-in validators cover common rules like required, minimum length, and email format. Your own rules, such as "no spaces in a username" or "the code must start with a prefix", need a custom validator. In Signal Forms you write one with validate() inside the schema function.
The validate() function
validate() takes a field path and a callback. The callback receives a context object and returns one of two things:
nullwhen the value is valid.- An error object with a
kindand amessagewhen it is not.
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 }) =>
/\s/.test(value())
? { kind: 'noSpaces', message: 'Username cannot contain spaces' }
: null
);
});value is a signal, so you call it as value(). The validator runs again whenever a signal it reads changes. You do not subscribe to anything or call an update method.
The kind string identifies the rule. The message is the text you show. In a template you read both from accountForm.username().errors(), as in the error display chapter.
Handle empty values
A custom validator also runs on an empty field. If your rule should only apply to typed input, return null for an empty value and let required() report the missing value. That way the user sees one error, not two.
validate(path.code, ({ value }) => {
if (value() === '') return null;
return value().startsWith('ID-')
? null
: { kind: 'prefix', message: 'Code must start with ID-' };
});Package a rule for reuse
If several fields share a rule, wrap validate() in a function. The function takes the field path as an argument, as the built-in validators do.
import { SchemaPath, validate } from '@angular/forms/signals';
export function noSpaces(path: SchemaPath<string>) {
validate(path, ({ value }) =>
/\s/.test(value())
? { kind: 'noSpaces', message: 'Spaces are not allowed' }
: null
);
}You then call noSpaces(path.username) in any schema function. The next chapters show how to read other fields and how to group rules into reusable schemas.
Common mistakes
- Returning
trueorfalseinstead ofnullor an error object. The callback must return one of those two shapes. - Forgetting the parentheses on
value(), which compares the signal itself and not the value. - Reusing one
kindfor different rules. The@forloop in the template tracks errors bykind, so duplicates cause confusing output.
Exercise
Write a validator for a nickname field that returns an error with kind tooShort when the value is non-empty but has fewer than 3 characters. What should it return for an empty value, and why?
Show answer
Call validate(path.nickname, ({ value }) => { if (value() === '') return null; return value().length >= 3 ? null : { kind: 'tooShort', message: 'Use at least 3 characters' }; }). It returns null for an empty value so that required() alone reports the missing value and the user does not see two errors.