Sub topic 7
Show validation errors to the user
A form that rejects input without saying why frustrates people. This chapter covers how to turn the errors() signal of a field into messages, when to show them, and how to make them accessible.
It assumes you can already create a form with form(), bind inputs with [field], and add built-in validators in a schema function. It also assumes you can read field state signals such as touched() and invalid(). Signal Forms is experimental in Angular 21, so check names such as Field against the release you use.
Where errors come from
Each field exposes an errors() signal. Its value is an array of error objects. An empty array means no validator is complaining. Each error has at least a kind string. It usually has a message string too.
The built-in validators set kind to their own name: required, email, minLength, and so on. If you pass a message option, it appears on the error object. If you don't, message is undefined, so a template that prints error.message shows nothing.
required(path.email, { message: 'Email is required' });
email(path.email); // no message: error.message is undefinedWhen you skip the message, you must supply the text somewhere else, usually by switching on kind. The two approaches are compared later in this chapter.
The basic display pattern
The pattern has three parts. Read the field's state, decide whether to show anything, then loop over the errors.
import { Component, signal } from '@angular/core';
import { form, Field, required, email, minLength } from '@angular/forms/signals';
@Component({
selector: 'app-signup',
imports: [Field],
template: `
<form (submit)="onSubmit($event)" novalidate>
<label for="email">Email</label>
<input
id="email"
type="email"
[field]="signupForm.email"
[attr.aria-invalid]="showEmailErrors() ? 'true' : null"
aria-describedby="email-errors"
/>
<div id="email-errors" aria-live="polite">
@if (showEmailErrors()) {
@for (error of signupForm.email().errors(); track error.kind) {
<p class="error">{{ error.message }}</p>
}
}
</div>
<label for="password">Password</label>
<input id="password" type="password" [field]="signupForm.password" />
<button type="submit">Sign up</button>
</form>
`,
})
export class SignupComponent {
private readonly model = signal({ email: '', password: '' });
protected readonly signupForm = form(this.model, (path) => {
required(path.email, { message: 'Email is required' });
email(path.email, { message: 'Enter a valid email address' });
required(path.password, { message: 'Password is required' });
minLength(path.password, 8, { message: 'Use at least 8 characters' });
});
protected showEmailErrors() {
const state = this.signupForm.email();
return state.touched() && state.invalid();
}
protected onSubmit(event: Event) {
event.preventDefault();
console.log(this.model());
}
}Three details matter here.
track error.kindworks because a field normally has at most one error of each kind. If a custom validator can return several errors of the same kind, track byerror.messageinstead, or by an index.- The
novalidateattribute turns off the browser's own validation bubbles, so your messages are the only ones the user sees. - The error container stays in the DOM and only its contents change. A screen reader watching an
aria-liveregion announces text that appears inside it. A region that is inserted along with its text is often not announced.
Decide when to show errors
Validation runs continuously. A new, empty form is already invalid, because the required validator fails on an empty value. If you display errors whenever invalid() is true, the user sees a wall of red before typing anything.
The usual gate is touched(). A field becomes touched when the user leaves it. The error then appears after the user finishes with the field instead of while they type.
| Condition | When messages appear | Trade-off | Column | Column |
|---|---|---|---|---|
| `invalid()` only | Immediately, on a pristine form | Noisy and hostile. Avoid it. | ||
| `touched() && invalid()` | After the user leaves the field | Good default. Errors can still sit unseen in fields the user never visited. | ||
| `dirty() && invalid()` | After the value changes | Errors show while the user is still typing. Fields that were skipped stay silent. | ||
| `(touched() \ | \ | submitAttempted()) && invalid()` | After blur, or after a submit attempt | Covers skipped fields. Needs one extra signal you maintain yourself. |
The last row needs a form-level flag. submit() marks every field as touched before it runs your action, so calling it already reveals all errors. Chapter code that uses submit() therefore gets the fourth behavior without extra state. A plain (submit) handler that never calls submit() does not mark fields as touched, so it needs its own flag or an explicit touch step.
Message text: on the validator or in the template
You can keep wording in the schema, as above, or map kind to text in the template layer.
Putting the message on the validator keeps rules and wording together. One schema change updates every place the field appears. The cost is that the schema now holds user-facing text, which matters if you translate your app.
Mapping in the template keeps the schema free of wording and gives you one place for internationalization. The cost is that every new kind needs an entry, or users see a blank line.
A small helper handles both. It prefers the validator's message and falls back to a lookup by kind.
const FALLBACK: Record<string, string> = {
required: 'This field is required.',
email: 'Enter a valid email address.',
minLength: 'This value is too short.',
};
export function messageFor(error: { kind: string; message?: string }): string {
return error.message ?? FALLBACK[error.kind] ?? 'This value is not valid.';
}The final default means an unknown kind never produces an empty paragraph.
Extract a reusable error component
Repeating the @if and @for blocks for every field gets tedious. A small component removes the duplication. It takes the errors array as an input, so it does not depend on any form class.
import { Component, input } from '@angular/core';
interface DisplayError {
kind: string;
message?: string;
}
@Component({
selector: 'app-field-errors',
template: `
<div aria-live="polite">
@for (error of errors(); track error.kind) {
<p class="error">{{ error.message ?? error.kind }}</p>
}
</div>
`,
})
export class FieldErrorsComponent {
readonly errors = input.required<readonly DisplayError[]>();
}In a template, you gate it with the same condition as before:
@if (signupForm.password().touched()) {
<app-field-errors [errors]="signupForm.password().errors()" />
}Here the live region is created inside the @if, which brings back the announcement problem described earlier. If screen reader output matters in your app, keep the aria-live container in the parent and put only the paragraphs inside the child component.
Errors that belong to the whole form
Some errors do not belong to one field, such as a failed server request. The form root has its own state, so signupForm().errors() returns the errors attached to the form itself. Errors you return from a submit() action are reported on the form, so you display them with the same loop:
@for (error of signupForm().errors(); track error.kind) {
<p class="error" role="alert">{{ error.message }}</p>
}Use role="alert" for submission failures. They are the result of something the user just did, so an immediate announcement is appropriate. For field messages, aria-live="polite" is usually the better choice.
To list every error in the form in one place, such as a summary above it, check whether your Angular version provides errorSummary() on the field state. It collects errors from the field and its descendants. Because the API is experimental, confirm the name and the shape of the returned objects before you rely on it.
Common mistakes
- Showing errors before interaction. Always gate on
touched()or an equivalent. Checking onlyinvalid()causes the problem described in the table above. - Reading
errors()outside a reactive context and expecting updates.errors()is a signal. Calling it once in a constructor gives a snapshot. Call it in the template or inside acomputed(). - Confusing
invalid()witherrors().length > 0. They are usually equivalent, but a field that is still waiting on async validation is neither valid nor invalid in the usual sense. Do not infer success from the absence of errors while validation is pending. - Relying on color alone. Pair a red border with text and
aria-invalid, so the error is visible to people who cannot distinguish colors and audible to screen readers.
Exercise
A user opens your form and clicks into the email field, types nothing, and tabs away. The schema has required(path.email, { message: 'Email is required' }), and the template shows errors only when touched() && invalid(). The same field also uses email(path.email) with no message option. Which messages appear, and what do you add to make sure the user never sees a blank error line?
Show answer
Only the required error is present, because an empty value fails required and the built-in email validator normally skips empty values. So 'Email is required' appears once the field is touched. If the user later types "abc", the email error appears with an undefined message, which renders as a blank paragraph. To prevent that, give email() a message option, or render text through a helper such as messageFor() that falls back to a lookup by kind and then to a generic sentence.