Sub topic 7
Showing validation messages at the right time
This chapter assumes you can already bind an input with ngModel, read control state through a template reference variable such as #name="ngModel", and apply required, minlength, and email. It covers when an error message should appear, how to write that rule once, and how to make the message reach screen reader users.
Why timing matters
A control that has required is invalid from the moment it renders, because its value is empty. If the template shows errors whenever invalid is true, the user sees "Name is required" before they have typed anything. That is noise, and it makes the form look broken.
The goal is to show a message only after the user has had a fair chance to fill in the field. Angular gives you three signals for this:
- The user has interacted with the field (
dirty). - The user has left the field (
touched). - The user has tried to submit the form (
NgForm.submitted).
The state flags
Each NgModel exposes boolean flags. Angular also toggles matching CSS classes on the element, which is useful for styling.
| Flag | True when | CSS class (true / false) |
|---|---|---|
| `pristine` / `dirty` | The user has not / has changed the value in the UI | `ng-pristine` / `ng-dirty` |
| `untouched` / `touched` | The control has not / has lost focus (blur event) | `ng-untouched` / `ng-touched` |
| `valid` / `invalid` | All validators pass / at least one fails | `ng-valid` / `ng-invalid` |
Two details cause confusion:
dirtyis set by user input. Changingmodel.namein code does not make the control dirty.touchedis set on blur. A user who tabs through an empty field makes it touched but not dirty.
For this reason, the common rule is invalid && (dirty || touched). It covers a user who typed something wrong and a user who skipped the field.
The decision flow
The diagram shows the check that runs on every change-detection pass for each control.
Writing the rule once
Repeating the three-part condition for every field is easy to get wrong. Put it in a component method and call it from the template. The full example below also adds the submitted case and the accessibility attributes discussed later.
import { Component } from '@angular/core';
import { FormsModule, NgForm, NgModel } from '@angular/forms';
@Component({
selector: 'app-contact',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit(f)">
<label for="name">Name</label>
<input
id="name"
name="name"
[(ngModel)]="model.name"
#nameCtrl="ngModel"
required
minlength="3"
[attr.aria-invalid]="shouldShow(nameCtrl, f) ? 'true' : null"
[attr.aria-describedby]="shouldShow(nameCtrl, f) ? 'name-errors' : null"
/>
@if (shouldShow(nameCtrl, f)) {
<div id="name-errors" role="alert">
@if (nameCtrl.errors?.['required']) {
<p>Name is required.</p>
}
@if (nameCtrl.errors?.['minlength']) {
<p>
Name needs at least
{{ nameCtrl.errors?.['minlength'].requiredLength }} characters
(now {{ nameCtrl.errors?.['minlength'].actualLength }}).
</p>
}
</div>
}
<label for="email">Email</label>
<input
id="email"
name="email"
type="email"
[(ngModel)]="model.email"
#emailCtrl="ngModel"
required
email
[attr.aria-invalid]="shouldShow(emailCtrl, f) ? 'true' : null"
[attr.aria-describedby]="shouldShow(emailCtrl, f) ? 'email-errors' : null"
/>
@if (shouldShow(emailCtrl, f)) {
<div id="email-errors" role="alert">
@if (emailCtrl.errors?.['required']) {
<p>Email is required.</p>
}
@if (emailCtrl.errors?.['email']) {
<p>Enter a valid email address.</p>
}
</div>
}
<button type="submit">Send</button>
</form>
`,
})
export class ContactComponent {
model = { name: '', email: '' };
shouldShow(control: NgModel, form: NgForm): boolean {
return (
!!control.invalid &&
(!!control.dirty || !!control.touched || form.submitted)
);
}
onSubmit(form: NgForm) {
if (form.invalid) {
return;
}
console.log('Submitted', this.model);
}
}Points to notice in this code:
shouldShowtakes theNgModeland theNgForm. The template variablesnameCtrlandfare passed in, so the method needs no@ViewChild.form.submittedbecomes true on the first submit attempt and stays true untilresetForm(). This is how an untouched, empty required field gets its message when the user clicks Send right away.errors?.['minlength']uses bracket access. With strict templates, the index signature onValidationErrorsrequires brackets.- The
minlengtherror object carriesrequiredLengthandactualLength, so the message can quote real numbers.
Why guard `onSubmit`
Angular adds novalidate to forms that use NgForm, which turns off the browser's own validation bubbles. It does not stop ngSubmit from firing on an invalid form. Without the if (form.invalid) return; check, invalid data reaches your save logic. The guard plus form.submitted gives the user feedback instead of silence.
Making messages accessible
Showing text on screen is not enough for users of screen readers. Three attributes help:
role="alert"on the message container makes assistive technology announce the text when it is inserted into the page. Because the@ifblock adds it only when it should be visible, the announcement happens at the right moment.aria-invalid="true"marks the input as having a problem. The example binds it with[attr.aria-invalid]and setsnullwhen there is no error, which removes the attribute instead of writing"false".aria-describedbypoints to the id of the message container, so focusing the input reads the error along with the label.
Also keep a visible <label for> on every input and do not rely on color. A red border from ng-invalid.ng-touched is fine as a supplement, but the text must carry the meaning.
Common mistakes
- Missing
nameattribute. Inside a<form>,ngModelregisters the control under itsname. Without it, Angular throws an error at runtime, and the control is not part off.valueorf.invalid. - Reading
errors.requireddirectly.errorsisnullwhen the control is valid. Useerrors?.['required'], or checkinvalidfirst. - Using the variable outside its scope.
#nameCtrlis visible in the whole template of the component, but if you declare it inside an@ifor@forblock, it is visible only inside that block. - Expecting
dirtyafter a programmatic change. Settingmodel.name = 'x'in code leaves the control pristine. Messages for such values appear only after the user touches the field or submits. - Showing every error at once. A value can fail several validators. If that is too much text, show only the first, for example with
@if/@else ifchains in priority order. - Cross-field messages on the wrong object. A group-level error is on the group's
errors, not on either input. The rule above applies to the group too, but you must pass the group'sNgModelGroupor the form, not a child control.
Timing with `updateOn`
By default, validity updates on every keystroke, so a minlength error can appear while the user is still typing the third character. If you set [ngModelOptions]="{ updateOn: 'blur' }", the control's value and validity update only when the field loses focus. The messages then match the touched rule naturally. A later chapter covers ngModelOptions in full. For now, remember that shouldShow reads state, so it works with any update strategy.
Exercise
A user opens the contact form above and clicks Send without typing anything. Which of dirty, touched, and form.submitted is true for the name control, and does the "Name is required." message appear? What changes if the template used only nameCtrl.invalid && (nameCtrl.dirty || nameCtrl.touched)?
Show answer
The name control is still pristine and untouched, so dirty and touched are both false. form.submitted is true because the submit event fired. With shouldShow, the message appears, since the condition includes form.submitted. With the shorter condition, no message appears, and the user clicking Send would get no feedback because onSubmit just returns on an invalid form. The control would also not be touched by clicking the button, because focus never entered the input.
Exercise
Why does the example bind [attr.aria-invalid] to 'true' or null instead of to a boolean such as shouldShow(nameCtrl, f)?
Show answer
A boolean binding on an attribute would write the strings "true" and "false". Using null removes the attribute entirely when there is no error. That keeps the markup clean, and the control is not announced as "invalid: false" on every field.