Sub topic 3
Write custom validators
Assume TypeScript, standalone Angular components, templates, signals, and basic form validation. Signal Forms is experimental in Angular 21, so verify API names against your Angular version.
Write custom and cross-field validators
A custom validator passed to validate() returns null when a value is valid. Otherwise, it returns an error object:
import { signal } from '@angular/core';
import { form, minLength, validate } from '@angular/forms/signals';
const model = signal({ password: '', confirm: '' });
const signupForm = form(model, (path) => {
minLength(path.password, 8, { message: 'Use at least 8 characters' });
validate(path.confirm, ({ value, valueOf }) =>
value() === valueOf(path.password)
? null
: { kind: 'mismatch', message: 'Passwords must match' }
);
});value() reads the current field. valueOf(path.password) reads another field, making cross-field rules reactive.
Conditional field state
Schema rules can derive state from other values. For example, disabled() can turn off a coupon field, while hidden() and readonly() can control visibility and editing. Use required() with when when validation only applies in a particular state.
disabled(path.coupon, ({ valueOf }) => !valueOf(path.hasCoupon));
required(path.coupon, {
when: ({ valueOf }) => valueOf(path.hasCoupon),
message: 'Enter your coupon code',
});The form model remains the source of truth, so conditional changes update automatically.
Reuse, asynchronous rules, and arrays
Extract a schema function when several forms share rules:
function accountRules(path: any) {
required(path.email);
email(path.email);
}Use validateAsync() for server-backed checks, such as checking whether a username is available. Debounce requests and handle failures as validation errors rather than treating network failure as success.
For repeated records, store an array in the model and use applyEach() to apply rules to every item. Each item receives its own field path, preserving independent errors and state.
Custom controls and migration
A custom control must expose the Signal Forms control contract, typically FormValueControl<T>, including its value, disabled state, and touched notification. Then consumers can bind it with [field] like a native input.
Migrate incrementally. Keep existing Reactive Forms screens working, create signal-backed models for new screens, and move one form at a time. Do not bind one field simultaneously to both APIs. Signal Forms has no promise of complete API stability while experimental.
Exercise
What should a custom validator return when its field is valid?
Show answer
It should return null. For an invalid value, it should return an error object with a kind and message.