Your own validation rules, rules that compare two fields or apply only sometimes, checks that ask a server, lists of fields you can add to and remove from, and submitting the form with errors from the server.
The built-in validators from Part 21 each look at one field. Real forms need more. A password has to contain a digit. A confirm box has to match the password. A company name is required only for business accounts. A username has to be free, and only the server knows that.
This part covers validate() for your own rules, rules that read another field, rules that apply only sometimes, async validation with validateAsync and validateHttp, lists of fields with applyEach, and submit(), including errors the server sends back. It builds on resource and httpResource from Part 19. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.
A quick recap of Part 21
A Signal Form starts from a model: a signal holding a plain object, like signal({ password: '', confirm: '' }). form(model, (p) => { ... }) wraps it in a field tree. The tree has the same shape as the model, so f.password is the password field. The function you pass is the schema. Its parameter is a tree of paths to each field (Part 21 named it path; here it’s p, to keep lines short), and you attach rules to them, like required(p.password). In the template, [formField]="f.password" binds an input to that field, both ways. Calling a field gives its state: f.password().value(), errors(), touched(), valid(), and f() is the state of the whole form. Everything in this part adds to that.
Try this first
Paste this into src/app/app.ts. Both fields are required.
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form, FormField, required } from '@angular/forms/signals';
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label>Password <input type="password" [formField]="f.password" /></label>
<label>Confirm <input type="password" [formField]="f.confirm" /></label>
<p>Form valid: {{ f().valid() }}</p>
`,
})
export class App {
protected readonly model = signal({ password: '', confirm: '' });
protected readonly f = form(this.model, (p) => {
required(p.password);
required(p.confirm);
});
}
Before you read on, guess. Type secret1 as the password and secret2 in the confirm box. Is the form valid?
It is. The page shows:
Password Confirm
Form valid: true
Both fields have a value, and that’s all we asked for. No built-in rule knows that one field has to match another. We have to write that rule ourselves.
validate(): your own rule
validate(path, fn) attaches a rule to one field. Angular calls fn with a context object for that field. Its value is a signal holding the field’s value. Your function returns null (or undefined) when the value is fine, and an error object when it isn’t.
An error object needs a kind: a short name you choose, which says what went wrong. The built-in validators use kinds like required and minLength. It can also have a message for the user.
Here’s a password that must contain a digit:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form, FormField, minLength, validate } from '@angular/forms/signals';
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label>Password <input type="password" [formField]="f.password" /></label>
@for (error of f.password().errors(); track error.kind) {
<p>{{ error.kind }}: {{ error.message }}</p>
}
`,
})
export class App {
protected readonly model = signal({ password: '' });
protected readonly f = form(this.model, (p) => {
minLength(p.password, 6, { message: 'Use at least 6 characters' });
validate(p.password, ({ value }) =>
/\d/.test(value()) ? null : { kind: 'needsDigit', message: 'Add at least one digit' },
);
});
}
({ value }) picks the value signal out of the context, so we can call value(). /\d/.test(...) is plain JavaScript: it’s true when the text contains a digit. To keep the demos short, this part shows errors straight away. In a real form, show them after the field is touched, as in Part 21.
Type abc. The page shows:
Password
minLength: Use at least 6 characters
needsDigit: Add at least one digit
Every rule on a field runs, and errors() lists every rule that failed. Type abcdef1, and both lines go:
Password
A validator works like a computed from Part 3. It reads signals, and Angular runs it again whenever one of them changes. You never call it yourself.
A rule that reads another field
The confirm box needs the password’s value. The context has valueOf(path) for that: it reads the value of any field in the form, by its path.
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form, FormField, required, validate } from '@angular/forms/signals';
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label>Password <input type="password" [formField]="f.password" /></label>
<label>Confirm <input type="password" [formField]="f.confirm" /></label>
@for (error of f.confirm().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
<p>Form valid: {{ f().valid() }}</p>
`,
})
export class App {
protected readonly model = signal({ password: '', confirm: '' });
protected readonly f = form(this.model, (p) => {
required(p.password);
required(p.confirm);
validate(p.confirm, ({ value, valueOf }) =>
value() === valueOf(p.password)
? null
: { kind: 'mismatch', message: "The passwords don't match" },
);
});
}
The rule sits on p.confirm, because that’s where the error should show. Type secret1 and secret2 again. The page shows:
Password Confirm
The passwords don't match
Form valid: false
Fix the confirm box to secret1, and the error goes. Now change the password to secret12. The page shows:
Password Confirm
The passwords don't match
Form valid: false
We didn’t touch the confirm box, but its error came back. valueOf(p.password) is a signal read, so the confirm rule depends on the password too, and it runs again when either one changes.
Rules that apply only sometimes
A sign-up form has a Business account box. Only business accounts need a company name. applyWhen(path, condition, schema) attaches a whole group of rules that count only while condition returns true:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { applyWhen, form, FormField, minLength, required } from '@angular/forms/signals';
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label><input type="checkbox" [formField]="f.business" /> Business account</label>
<label>Company <input [formField]="f.company" /></label>
@for (error of f.company().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
<p>Form valid: {{ f().valid() }}</p>
`,
})
export class App {
protected readonly model = signal({ business: false, company: '' });
protected readonly f = form(this.model, (p) => {
applyWhen(
p,
({ value }) => value().business,
(account) => {
required(account.company, { message: 'Enter the company name' });
minLength(account.company, 2, { message: 'Use at least 2 letters' });
},
);
});
}
applyWhen here is attached to p, the whole form, so value() in the condition is the whole model, and account is the form’s path tree again, for the rules inside the group. Its rules count only while the box is ticked. A checkbox bound with [formField] to a boolean field ticks and unticks it.
At first, the form is valid with an empty company:
Business accountCompany
Form valid: true
The page text runs the two labels together as Business accountCompany, because labels sit on one line.
Tick Business account. The page shows:
Business accountCompany
Enter the company name
Form valid: false
Untick it, and the error goes:
Business accountCompany
Form valid: true
For one rule, there’s a shorter way: required takes a when option, required(p.company, { when: ({ valueOf }) => valueOf(p.business) }). You’ll write one in Exercise 2. Use applyWhen when several rules share the same condition.
Async validation: asking a server
Is the username ana free? Only the server knows. A rule like that is async: the answer arrives later. validateAsync attaches one. It uses a resource from Part 19 to load the answer.
Our “server” is a function that answers after a short delay, like the ones in Part 19. It logs each name it checks:
// src/app/app.ts
import { Component, resource, signal } from '@angular/core';
import { form, FormField, minLength, required, validateAsync } from '@angular/forms/signals';
const TAKEN = ['ana', 'ben'];
function isTaken(name: string): Promise<boolean> {
console.log(`checking ${name}`);
return new Promise((resolve) => setTimeout(() => resolve(TAKEN.includes(name)), 500));
}
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label>Username <input [formField]="f.username" /></label>
@if (f.username().pending()) {
<p>Checking...</p>
}
@for (error of f.username().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
<p>valid: {{ f.username().valid() }}, invalid: {{ f.username().invalid() }}</p>
`,
})
export class App {
protected readonly model = signal({ username: '' });
protected readonly f = form(this.model, (p) => {
required(p.username, { message: 'Pick a username' });
minLength(p.username, 3, { message: 'Use at least 3 letters' });
validateAsync(p.username, {
params: ({ value }) => value(),
factory: (name) => resource({ params: name, loader: ({ params }) => isTaken(params) }),
onSuccess: (taken) => (taken ? { kind: 'taken', message: 'That name is taken' } : null),
onError: () => ({ kind: 'checkFailed', message: "We couldn't check that name" }),
});
});
}
validateAsync takes four functions:
paramssays what to check. Here it’s the field’s value.factorybuilds the resource. Angular hands itname, a signal of the params, and you pass that straight toresourceas itsparams. When the username changes, the resource loads again, as in Part 19.onSuccessturns the loaded value into an error, ornull.onErrorturns a failed load into an error. It isn’t optional, so you have to decide what a failed check means.
Type an. The page shows:
Username
Use at least 3 letters
valid: false, invalid: true
Now type ana. Straight away, the page shows:
Username
Checking...
valid: false, invalid: false
While the check runs, the field is pending. pending() is true. valid() and invalid() are both false: there’s no error yet, but it isn’t proven valid either. So valid() isn’t the same as “not invalid()“. Wait a moment, and the answer arrives:
Username
That name is taken
valid: false, invalid: true
Type cyd, wait, and the page shows:
Username
valid: true, invalid: false
The console shows each name the server was asked about:
checking ana
checking cyd
an was never sent. Async validation runs only when every synchronous rule on the field passes, so the server isn’t asked about a name that’s already wrong. That’s also why we added required. Without it, the empty field passes every synchronous rule, and the page would ask the server about an empty name as soon as it loads.
An async rule waits for the sync rules. While it runs, the field is pending: not valid, and not invalid.
Here are those steps in words, in case the animation doesn’t play for you:
- You type
an.minLengthfails, so the field is invalid, and the async rule doesn’t run. The server is never asked. - You type
cyd. Every sync rule passes, so the resource loads and asks the server. The field is pending:pending()is true, andvalid()andinvalid()are both false. The template shows “Checking…”. - The server answers
false: the name is free.onSuccessreturnsnull, pending ends, and the field is valid.
validateHttp: the same check over HTTP
A real check asks a real server. validateHttp is validateAsync with an httpResource built in. Instead of params and factory, you give it request, a function that returns the URL to load.
We have no server, so we’ll use a file in public/, as in Part 18. Create public/users.json:
["ana", "ben", "cy"]
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form, FormField, required, validateHttp } from '@angular/forms/signals';
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label>Username <input [formField]="f.username" /></label>
@for (error of f.username().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
<p>valid: {{ f.username().valid() }}</p>
`,
})
export class App {
protected readonly model = signal({ username: '' });
protected readonly f = form(this.model, (p) => {
required(p.username, { message: 'Pick a username' });
validateHttp(p.username, {
request: ({ value }) => `/users.json?name=${value()}`,
onSuccess: (names: string[], { value }) =>
names.includes(value()) ? { kind: 'taken', message: 'That name is taken' } : null,
onError: () => ({ kind: 'checkFailed', message: "We couldn't check that name" }),
});
});
}
A real server would answer for one name: /api/check-username?name=ana. Our file holds the whole list, so onSuccess looks the name up itself. It gets the loaded JSON and the field’s context, the same context validate gets. names: string[] tells TypeScript what the JSON holds. The ?name= part still matters: it makes the URL change with the name, so the resource loads again for each new name.
Type ana and wait. The page shows:
Username
That name is taken
valid: false
Type dev and wait, and it shows:
Username
valid: true
Both functions take one more option worth knowing: debounce, a number of milliseconds to wait before the check starts. It’s meant for fast typists, so a check doesn’t start for every key they press. They also take when, a function that returns false when the check shouldn’t run at all.
Lists of fields: arrays and applyEach
A party invitation has a list of guests. You can add a guest and remove one. In the model, that’s an array, and the field tree has one field per item: f.guests[0].name, f.guests[1].name, and so on. You can loop over f.guests with @for.
applyEach(path, schema) attaches rules to every item, including ones added later:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { applyEach, form, FormField, required } from '@angular/forms/signals';
interface Guest {
name: string;
}
@Component({
selector: 'app-root',
imports: [FormField],
template: `
@for (guest of f.guests; track guest; let i = $index) {
<div>
<label>Guest {{ i + 1 }} <input [formField]="guest.name" /></label>
<button (click)="remove(i)">Remove</button>
</div>
@for (error of guest.name().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
}
<button (click)="add()">Add guest</button>
<p>{{ f.guests.length }} guests, valid: {{ f().valid() }}</p>
`,
})
export class App {
protected readonly model = signal<{ guests: Guest[] }>({ guests: [{ name: 'Ana' }] });
protected readonly f = form(this.model, (p) => {
applyEach(p.guests, (guest) => {
required(guest.name, { message: 'Enter a name' });
});
});
protected add() {
this.model.update((m) => ({ guests: [...m.guests, { name: '' }] }));
}
protected remove(index: number) {
this.model.update((m) => ({ guests: m.guests.filter((_, i) => i !== index) }));
}
}
Some things to notice:
- To add or remove a row, change the model, with a new array as in Part 3. The field tree follows. There’s no separate “add field” call.
applyEachgets a function whoseguestis the path to one item. The rules inside apply to every item.track guesttracks each row by its field. Angular keeps the same field for the same item object when the list changes, so@for(Part 4) keeps each input with its guest.filter((_, i) => i !== index)keeps every item except the one atindex. The_is a name for the item we don’t use.
Click Add guest. The new row is empty, so its required rule fails straight away. The page shows:
Guest 1 Remove
Guest 2 Remove
Enter a name
Add guest
2 guests, valid: false
Type Ben into Guest 2, then click the first Remove. Ana goes, and Ben moves up to Guest 1:
Guest 1 Remove
Add guest
1 guests, valid: true
The input in that row now holds Ben. (Input values aren’t part of the page text, so you’ll see that in the browser, not in the text above.) (And yes, “1 guests”. Exercise 3 changes that line.)
submit(): sending the form
submit(form, action) runs the steps every form needs when the user presses Save:
- It marks every field the user can fill in as touched, so any error you show after touching appears now.
- If the form has errors, it stops there and returns
false. Your action doesn’t run. - Otherwise it runs your
action, anasyncfunction that sends the data. While it runs,submitting()is true. - It returns
trueif the action reported no errors.
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { email, form, FormField, required, submit } from '@angular/forms/signals';
function saveToServer(data: { email: string }): Promise<void> {
console.log(`saving ${data.email}`);
return new Promise((resolve) => setTimeout(resolve, 500));
}
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label>Email <input type="email" [formField]="f.email" /></label>
@if (f.email().touched()) {
@for (error of f.email().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
}
<button (click)="save()" [disabled]="f().submitting()">Save</button>
@if (f().submitting()) {
<p>Saving...</p>
}
`,
})
export class App {
protected readonly model = signal({ email: '' });
protected readonly f = form(this.model, (p) => {
required(p.email, { message: 'Enter your email' });
email(p.email, { message: 'That is not an email address' });
});
protected async save() {
const ok = await submit(this.f, async (form) => {
await saveToServer(form().value());
return null;
});
console.log(`submitted: ${ok}`);
}
}
The action gets the field tree, here named form, so form().value() is the whole model. It returns null when all went well. We’ll return errors from it in a moment.
Click Save with the field empty. The error appears, though you never touched the field:
Email
Enter your email
Save
The console shows:
submitted: false
Type ana@example.com and click Save. Straight away the button is disabled and the page shows:
Email Save
Saving...
When the save finishes, “Saving…” goes, and the console has two more lines:
saving ana@example.com
submitted: true
submit also refuses to start while the same form is still submitting: a second call returns false without running the action. Disabling the button tells the user why nothing happens.
Errors from the server
The server may still say no. Someone took the username a second after our check said it was free. To show that on the field, the action returns errors. Each one names its field with fieldTree:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form, FormField, required, submit } from '@angular/forms/signals';
function register(name: string): Promise<boolean> {
return new Promise((resolve) => setTimeout(() => resolve(name !== 'cy'), 300));
}
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label>Username <input [formField]="f.username" /></label>
@for (error of f.username().errors(); track error.kind) {
<p>{{ error.kind }}: {{ error.message }}</p>
}
<button (click)="save()">Sign up</button>
`,
})
export class App {
protected readonly model = signal({ username: '' });
protected readonly f = form(this.model, (p) => {
required(p.username, { message: 'Pick a username' });
});
protected async save() {
await submit(this.f, async (form) => {
const ok = await register(form.username().value());
return ok ? null : { kind: 'server', message: 'Just taken', fieldTree: form.username };
});
}
}
Type cy and click Sign up. After the answer, the page shows:
Username
server: Just taken
Sign up
The error sits in errors() like any other, so the template needs nothing new. It stays until the field’s value changes. Type cyd, and it’s gone:
Username Sign up
An error with no fieldTree goes on the field you submitted, here the whole form.
Submitting from a form element
So far a button called submit(). You can also put the action in the form itself, with a third argument to form(): { submission: { action } }. Then add the FormRoot directive to a <form> element, as <form [formRoot]="f">. When the form is submitted, by a type="submit" button or Enter in a field, FormRoot stops the browser’s own page reload and calls submit() for you. Without submission, FormRoot only stops the reload, and nothing is sent. The worked example below uses it.
Worked example: a validator that returns a string
A first try at a rule often returns the message itself:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form, FormField, validate } from '@angular/forms/signals';
@Component({
selector: 'app-root',
imports: [FormField],
template: `<label>Name <input [formField]="f.name" /></label>`,
})
export class App {
protected readonly model = signal({ name: '' });
protected readonly f = form(this.model, (p) => {
validate(p.name, ({ value }) => (value().length < 3 ? 'Too short' : null));
});
}
ng serve stops:
✘ [ERROR] TS2322: Type '"Too short" | null' is not assignable to type 'ValidationResult<WithoutFieldTree>'.
Type '"Too short"' is not assignable to type 'ValidationResult<WithoutFieldTree>'. [plugin angular-compiler]
Read it from the inside out:
Type '"Too short" | null'is what our function returns: either that exact string ornull. The|means “or”.ValidationResult<WithoutFieldTree>is whatvalidatewants. AValidationResultis “no error” (null,undefined) or one or more error objects.WithoutFieldTreemeans the errors can’t name another field: avalidaterule only puts errors on its own field.- The second line narrows it down: the
nullpart is fine, the string is the problem.
The fix is to return an error object with a kind:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form, FormField, validate } from '@angular/forms/signals';
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label>Name <input [formField]="f.name" /></label>
@for (error of f.name().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
`,
})
export class App {
protected readonly model = signal({ name: '' });
protected readonly f = form(this.model, (p) => {
validate(p.name, ({ value }) =>
value().length < 3 ? { kind: 'tooShort', message: 'Too short' } : null,
);
});
}
Type al. The page shows:
Name
Too short
The kind is worth the extra words. A template can show a different message per kind, and a test can check for tooShort without caring how the message is worded.
Worked example: a sign-up form
Now everything together: a username checked against public/users.json, a password with a digit, a confirm box that must match, and a submit through <form [formRoot]>. The “server” rejects dev, to show a server error.
["ana", "ben", "cy"]
// src/app/app.ts
import { Component, signal } from '@angular/core';
import {
form,
FormField,
FormRoot,
minLength,
required,
validate,
validateHttp,
} from '@angular/forms/signals';
interface SignUp {
username: string;
password: string;
confirm: string;
}
function createAccount(data: SignUp): Promise<boolean> {
console.log(`creating ${data.username}`);
return new Promise((resolve) => setTimeout(() => resolve(data.username !== 'dev'), 300));
}
@Component({
selector: 'app-root',
imports: [FormField, FormRoot],
template: `
<form [formRoot]="f">
<label>Username <input [formField]="f.username" /></label>
<label>Password <input type="password" [formField]="f.password" /></label>
<label>Confirm <input type="password" [formField]="f.confirm" /></label>
<button type="submit" [disabled]="f().submitting()">Sign up</button>
</form>
@for (error of f().errorSummary(); track error) {
<p>{{ error.message }}</p>
}
<p>{{ result() }}</p>
`,
})
export class App {
protected readonly model = signal<SignUp>({ username: '', password: '', confirm: '' });
protected readonly result = signal('');
protected readonly f = form(
this.model,
(p) => {
required(p.username, { message: 'Pick a username' });
validateHttp(p.username, {
request: ({ value }) => `/users.json?name=${value()}`,
onSuccess: (names: string[], { value }) =>
names.includes(value()) ? { kind: 'taken', message: 'That name is taken' } : null,
onError: () => ({ kind: 'checkFailed', message: "We couldn't check that name" }),
});
minLength(p.password, 6, { message: 'Use at least 6 characters' });
validate(p.password, ({ value }) =>
/\d/.test(value()) ? null : { kind: 'needsDigit', message: 'Add a digit' },
);
validate(p.confirm, ({ value, valueOf }) =>
value() === valueOf(p.password)
? null
: { kind: 'mismatch', message: "The passwords don't match" },
);
},
{
submission: {
action: async (form) => {
const ok = await createAccount(form().value());
if (!ok) {
return { kind: 'server', message: 'Try another name', fieldTree: form.username };
}
this.result.set(`Welcome, ${form.username().value()}!`);
return null;
},
},
},
);
}
New here:
form(model, schema, options): the third argument holdssubmission, with the sameactionas before.<form [formRoot]="f">and atype="submit"button. Clicking it submits the form, andFormRootruns our action. No(click)handler.f().errorSummary()lists the errors of the whole form, every field included, so one list at the bottom shows them all.errors()onf()would only list errors on the form object itself.- The
resultsignal is a field like any other. The action can set it, because the arrow function seesthis.
Click Sign up straight away. Nothing is sent, and the page shows:
Username Password Confirm Sign up
Pick a username
Add a digit
There’s no “Use at least 6 characters”. As Part 21 showed, minLength leaves an empty value alone; saying a field can’t be empty is required‘s job. Our digit rule has no such exception, so it complains. The confirm box matches the empty password, so it’s quiet too.
Fill it in with a taken name: username ana, password secret1 twice. The check runs as you type, and the page shows:
Username Password Confirm Sign up
That name is taken
Change the username to dev. The check says it’s free, so click Sign up. The server says no:
Username Password Confirm Sign up
Try another name
Change it to dev2, wait for the check, and press Enter in the field. That submits the form too:
Username Password Confirm Sign up
Welcome, dev2!
The console shows the two tries that reached the server:
creating dev
creating dev2
Worked example: when the check itself fails
What if the check can’t reach the server? Rename public/users.json to public/names.json and keep the code asking for /users.json. Here’s the code from the validateHttp section again, with no file in public/:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form, FormField, required, validateHttp } from '@angular/forms/signals';
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label>Username <input [formField]="f.username" /></label>
@for (error of f.username().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
<p>valid: {{ f.username().valid() }}</p>
`,
})
export class App {
protected readonly model = signal({ username: '' });
protected readonly f = form(this.model, (p) => {
required(p.username, { message: 'Pick a username' });
validateHttp(p.username, {
request: ({ value }) => `/users.json?name=${value()}`,
onSuccess: (names: string[], { value }) =>
names.includes(value()) ? { kind: 'taken', message: 'That name is taken' } : null,
onError: () => ({ kind: 'checkFailed', message: "We couldn't check that name" }),
});
});
}
Type ana and wait. The page shows:
Username
We couldn't check that name
valid: false
and the browser’s console has a red line:
Failed to load resource: the server responded with a status of 404 (Not Found)
Read the two together:
- The console line comes from the browser, not Angular.
404 (Not Found)means the server has no file at that address. In the Network tab of the developer tools, the failed request shows the full URL,/users.json?name=ana. Compare it with what’s inpublic/. - The page message comes from our
onError. The load failed, soonSuccessnever ran, andonErrordecided what the user sees.
onError returned an error, so the field is invalid and the form can’t be submitted. That’s the safe choice for a username. For a check that only warns, such as “this email looks unusual”, onError could return null and let the form through.
Best practices
- Give every custom error a
kindand amessage. Thekindis what code checks, the message is what people read. It replaces returning bare strings, which doesn’t build. - Put a cross-field rule on the field that shows the error.
validate(p.confirm, ...)withvalueOf(p.password)shows the error under the confirm box and re-runs when either field changes. It replaces checking both fields in a submit handler. - Keep sync rules in front of async ones. Async validation waits until the sync rules pass, so
requiredandminLengthsave a request for every empty or short value. Adddebounceto send fewer requests while someone types. - Change arrays through the model. Add and remove items with
updateand a new array;applyEachcovers new items for you. It replaces building fields by hand. - Let
submit()do the bookkeeping. It touches every field, skips the action on errors, trackssubmitting(), and puts server errors on fields. It replaces hand-writtenloadingflags and error maps.
Tips and traps
- Treating
!invalid()as “valid”. While an async check runs,invalid()is false butvalid()is false too. Usevalid()when you mean “proven OK”, andpending()to show “Checking…”. - Submitting while a check is pending. By default,
submit()runs the action if nothing is invalid, so a pending check doesn’t stop it. If a pending check should block sending, pass{ action, ignoreValidators: 'none' }tosubmit(): it then returnsfalsewithout running the action while a check is pending (it doesn’t wait for it). Or keep the button disabled whilef().pending(). - Async checks for an empty field. Without
required, an empty value passes every sync rule, and the check runs for''when the page loads. Addrequired, use thewhenoption, or returnundefinedfromrequestto skip the check. - Changing the field tree instead of the model. There’s no
pushonf.guests. Add and remove items in the model signal; the fields follow. - Using
errors()on the form and finding it empty.f().errors()holds only errors on the form object itself. For every field’s errors, usef().errorSummary(). - A server error that won’t go away. It stays until that field’s value changes. If the problem was elsewhere, target that field with
fieldTree, or leavefieldTreeoff to put the error on the form.
A rule is a function of signals that returns an error or nothing; Angular decides when to run it.
Exercises
Exercise 1. Add a rule to this form: a username can’t contain a space. Use validate with the kind noSpaces and the message “No spaces, please”. Hint: value().includes(' ').
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form, FormField, required } from '@angular/forms/signals';
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label>Username <input [formField]="f.username" /></label>
@for (error of f.username().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
`,
})
export class App {
protected readonly model = signal({ username: '' });
protected readonly f = form(this.model, (p) => {
required(p.username, { message: 'Pick a username' });
});
}
Exercise 2. A form has a business checkbox and a vat field for a tax number. Make vat required only for business accounts, with the when option of required instead of applyWhen. Show the form’s valid() and check it before and after ticking the box.
Exercise 3. In the guest list, allow at most 3 guests. Add a validate rule on p.guests itself (the whole array) that returns { kind: 'tooMany', message: 'At most 3 guests' } when there are more than 3, and show the errors of f.guests(). Also fix the “1 guests” line, so it says “1 guest”. Hint: @if from Part 4 or the ? : from Part 2.
Answers
1. Add a second rule. Both run, so an empty name gets the required message and a name with a space gets ours:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form, FormField, required, validate } from '@angular/forms/signals';
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label>Username <input [formField]="f.username" /></label>
@for (error of f.username().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
`,
})
export class App {
protected readonly model = signal({ username: '' });
protected readonly f = form(this.model, (p) => {
required(p.username, { message: 'Pick a username' });
validate(p.username, ({ value }) =>
value().includes(' ') ? { kind: 'noSpaces', message: 'No spaces, please' } : null,
);
});
}
Type ana b. The page shows:
Username
No spaces, please
2. when gets the same context as a validator, so valueOf(p.business) reads the checkbox:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { form, FormField, required } from '@angular/forms/signals';
@Component({
selector: 'app-root',
imports: [FormField],
template: `
<label><input type="checkbox" [formField]="f.business" /> Business account</label>
<label>VAT number <input [formField]="f.vat" /></label>
<p>Form valid: {{ f().valid() }}</p>
`,
})
export class App {
protected readonly model = signal({ business: false, vat: '' });
protected readonly f = form(this.model, (p) => {
required(p.vat, { when: ({ valueOf }) => valueOf(p.business) });
});
}
At first the page shows:
Business accountVAT number
Form valid: true
Tick Business account, and it shows:
Business accountVAT number
Form valid: false
3. A rule on the array is an ordinary validate; its value() is the whole array. Its errors sit on f.guests(), not on any one guest:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { applyEach, form, FormField, required, validate } from '@angular/forms/signals';
interface Guest {
name: string;
}
@Component({
selector: 'app-root',
imports: [FormField],
template: `
@for (guest of f.guests; track guest; let i = $index) {
<div>
<label>Guest {{ i + 1 }} <input [formField]="guest.name" /></label>
<button (click)="remove(i)">Remove</button>
</div>
}
<button (click)="add()">Add guest</button>
@for (error of f.guests().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
<p>{{ f.guests.length }} {{ f.guests.length === 1 ? 'guest' : 'guests' }}</p>
`,
})
export class App {
protected readonly model = signal<{ guests: Guest[] }>({ guests: [{ name: 'Ana' }] });
protected readonly f = form(this.model, (p) => {
applyEach(p.guests, (guest) => {
required(guest.name, { message: 'Enter a name' });
});
validate(p.guests, ({ value }) =>
value().length > 3 ? { kind: 'tooMany', message: 'At most 3 guests' } : null,
);
});
protected add() {
this.model.update((m) => ({ guests: [...m.guests, { name: '' }] }));
}
protected remove(index: number) {
this.model.update((m) => ({ guests: m.guests.filter((_, i) => i !== index) }));
}
}
At first the page shows:
Guest 1 Remove
Add guest
1 guest
Click Add guest three times. The page shows:
Guest 1 Remove
Guest 2 Remove
Guest 3 Remove
Guest 4 Remove
Add guest
At most 3 guests
4 guests
What’s next
Signal Forms are what new Angular code uses, but most existing apps were built with reactive forms. In Part 23, we’ll read FormGroup, FormControl and Validators, so you can work in those apps and see how they map to what you know now.