Sub topic 10
Validate across fields
Some rules cannot be checked by looking at one field alone. A confirmation password must equal the password. An end date must come after the start date. This chapter shows how to write those rules in a schema function, where the error appears, and the mistakes that cause stale or duplicate messages.
It assumes you know the earlier chapters: a signal model, form(), the [field] binding, built-in validators, and the shape of a custom validator. Signal Forms is experimental in Angular 21, so names may change in later releases.
The idea: read a sibling with valueOf()
A custom validator created with validate() receives a context object. Two members matter here:
value()is the signal holding the value of the field being validated.valueOf(path)returns the current value of any other field in the same form, addressed by its schema path.
A cross-field rule is an ordinary custom validator that calls valueOf() on another field. The validator returns null when the field is valid. Otherwise it returns an error object with a kind and a message.
import { signal } from '@angular/core';
import { form, required, minLength, validate } from '@angular/forms/signals';
const model = signal({ password: '', confirm: '' });
const signupForm = form(model, (path) => {
required(path.password);
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' }
);
});The rule is attached to path.confirm. The error therefore belongs to the confirm field, and signupForm.confirm().errors() lists it. This is usually what you want, because the message appears next to the input the user has to fix.
Why it stays up to date
You do not need to subscribe to the password field or trigger a re-check by hand. Validators run inside a reactive context. Calling valueOf(path.password) reads the password signal, so the validator depends on it. When the password changes, the validator for confirm runs again.
Consider a user who types a password, types a matching confirmation, and then edits the password. The confirm field becomes invalid immediately, even though the user never touched it. With Reactive Forms you had to call updateValueAndValidity() on the other control to get this behavior.
The block above is intentionally not used. The diagram follows.
Showing the error
Read the errors from the field that owns the rule. Gate the message on touched() so it does not appear before the user has visited the field.
import { Component, signal } from '@angular/core';
import { form, Field, required, minLength, validate } from '@angular/forms/signals';
@Component({
selector: 'app-signup',
imports: [Field],
template: `
<form (submit)="onSubmit($event)">
<label>Password <input type="password" [field]="signupForm.password" /></label>
<label>Confirm <input type="password" [field]="signupForm.confirm" /></label>
@if (signupForm.confirm().touched() && signupForm.confirm().invalid()) {
@for (error of signupForm.confirm().errors(); track error.kind) {
<p class="error">{{ error.message }}</p>
}
}
<button type="submit" [disabled]="signupForm().invalid()">Sign up</button>
</form>
`,
})
export class SignupComponent {
private readonly model = signal({ password: '', confirm: '' });
protected readonly signupForm = form(this.model, (path) => {
required(path.password);
minLength(path.password, 8, { message: 'Use at least 8 characters' });
required(path.confirm, { message: 'Confirm your password' });
validate(path.confirm, ({ value, valueOf }) =>
value() === valueOf(path.password)
? null
: { kind: 'mismatch', message: 'Passwords must match' }
);
});
protected onSubmit(event: Event) {
event.preventDefault();
console.log(this.model());
}
}The submit button uses signupForm().invalid(), the state of the whole form. A mismatch on confirm makes the form invalid, so the button is disabled.
Choosing which field owns the error
A rule that involves two fields must be attached to one of them. Pick the field where the user can fix the problem and where the message reads naturally.
| Rule | Attach to | Reason |
|---|---|---|
| Confirm equals password | `confirm` | The user retypes the confirmation. |
| End date is after start date | `end` | The message reads "End must be after start". |
| Maximum is at least minimum | `max` | The later field is usually edited last. |
| At least one of phone or email | The field the user is most likely to fill in | See the example below. |
The choice affects only where the error appears. The validator can read any field regardless of where it is attached.
Example: a date range
Dates in YYYY-MM-DD form compare correctly as strings, which keeps this example short. If your model holds Date objects or timestamps, compare those instead.
import { signal } from '@angular/core';
import { form, required, validate } from '@angular/forms/signals';
const model = signal({ start: '', end: '' });
const tripForm = form(model, (path) => {
required(path.start, { message: 'Pick a start date' });
required(path.end, { message: 'Pick an end date' });
validate(path.end, ({ value, valueOf }) => {
const start = valueOf(path.start);
const end = value();
if (!start || !end) {
return null;
}
return end >= start
? null
: { kind: 'dateRange', message: 'End date must not be before the start date' };
});
});The early return null matters. Without it, an empty end would be compared against start. The user would then see both "Pick an end date" from required() and a range error for the same empty field. Let required() own the empty case and have the cross-field rule run only when both values exist.
Making a rule apply only sometimes
A cross-field rule often applies only in certain situations. You have two ways to express that.
- Return
nullearly inside the validator, as the date example does. - Pass a
whenoption to a built-in validator, as inrequired(path.coupon, { when: ({ valueOf }) => valueOf(path.hasCoupon) }).
Use when with built-in validators, which keeps the schema readable. Use the early return in custom validators, where you already have the logic in hand.
Edge cases and common errors
- Reading the wrong path.
valueOf()takes a schema path such aspath.password, not a field from the form object such assignupForm.password. The schema function runs once while the form is built, so it can only refer to paths. - Comparing the wrong things.
value()is a function. Writingvalue === valueOf(path.password)compares a function to a string and is always false. Call it. - Duplicate messages. Two validators can both fail on the same empty field. Keep empty-value handling in
required()and skip empty inputs in your own rule. - Missing keys. Errors are tracked by
kind. If two custom validators on the same field both usekind: 'invalid', thetrack error.kindin the template will complain about duplicates. Give each rule a distinctkind. - Mutating the model in a validator. Validators should only read. Do not write to the model signal or call
set()inside one. Derive state withvalueOf()and return the result. - Expecting the error on the other field. A rule attached to
confirmdoes not put an error onpassword. If you want both inputs highlighted, you need a secondvalidate()call onpath.password, or a tree-level validator that can target child fields. Check the API reference for the Angular version you use, because the experimental API may rename or change these.
Comparison with Reactive Forms
In Reactive Forms, a cross-field rule is usually a validator on the parent FormGroup. It reads group.get('password') and group.get('confirm') and puts the error on the group. The template then has to check form.errors?.['mismatch'] separately from the control errors. With Signal Forms, the rule sits on the field that needs the message, and dependencies are tracked through signal reads. There is no group-level error to look up and no manual revalidation.
Exercise
A form has a min field and a max field. Write the validate() call that attaches to path.max and reports { kind: 'range', message: 'Max must be at least min' } when max is lower than min. It should return null if either value is an empty string. Why does the error update when the user edits min afterward?
Show answer
validate(path.max, ({ value, valueOf }) => { const min = valueOf(path.min); const max = value(); if (min === '' || max === '') { return null; } return Number(max) >= Number(min) ? null : { kind: 'range', message: 'Max must be at least min' }; }); The error updates because the validator calls valueOf(path.min), which reads the min signal. Validators run reactively, so any change to min makes the validator for max run again without extra code.
Exercise
A signup form shows "Passwords must match" on the confirm field, but it also shows "Confirm your password" when the field is empty. What causes the second message to appear alongside the first, and how do you fix it?
Show answer
Both required() and the custom mismatch validator fail on an empty confirm field, because an empty string differs from a non-empty password. Fix it by making the custom validator return null when the confirm value is empty, so required() alone reports the empty case.