Sub topic 9
When to validate
This chapter covers the timing of validation: on submit, on blur, or while the user types. It assumes you know basic HTML forms, can read JavaScript event handlers, and have read the earlier chapters on labels, hint text, and required fields. The next chapter covers the wording of error messages, so the messages here are short placeholders.
Why timing matters
Validation checks that a value is acceptable. Timing decides when the user finds out it is not. The same rule can feel helpful or hostile depending on when it speaks.
- Too early, and the form shows an error for something the user has not finished typing. The user sees "Enter a valid email" after typing one character.
- Too late, and the user fills in twenty fields, presses submit, and then learns that the first one was wrong.
- Too often, and the messages flicker, move the layout, and make screen readers repeat announcements.
Your goal is to report a problem at the first moment the user has had a fair chance to get it right.
The three common strategies
| Strategy | Event | Strength | Weakness |
|---|---|---|---|
| On submit | `submit` | Simple. Never interrupts typing. | Errors arrive in one batch, after all the effort. |
| On blur | `blur` or `change` | The user has finished the field. Feedback is close to the cause. | Can interrupt when the user tabs through a field on purpose. |
| While typing | `input` | Immediate. Good for counters and strength meters. | Flags incomplete values. Noisy for assistive technology. |
Validate on submit
On submit, you check everything when the user presses the button. This is the safest baseline, and the browser does it for you if you use constraint attributes such as required, type="email", pattern, min, and max.
Submit validation has a clear advantage: the user is always at a point where they expect a response. It never interrupts them. Its weakness is delayed feedback. On a long form, the user may have to scroll back to find which fields failed.
Treat submit validation as mandatory. Even if you also validate earlier, a user can press Enter in a field, skip a field, or paste a value without leaving it, so the submit check is your final gate.
Validate on blur
A field's blur event fires when it loses focus. At that point the user has signaled that they are done with it, so an error is fair. The feedback is also near the cause: the user is still looking at that field.
On-blur validation fits most fields that have a clear "complete" state, such as email, phone number, postcode, and date.
It has two known problems.
- Tabbing past a field. A keyboard user who tabs through a required field to reach a later one triggers an "Enter your email" error on a field they have not yet visited in earnest. If the user is only moving through the form, this can be annoying. A common fix is to validate a field only after the user has typed in it, or after a first failed submit.
- Shifting layout. An error that appears when you click a button can push that button down, so the click lands on the wrong element. Reserve space for messages or keep the error close to the field so the layout does not jump during the click.
Validate while typing
Validating on every input event gives the fastest feedback, but it judges the value before it is finished. An email field is invalid until the user types the domain, so flagging it on each keystroke produces errors that are true and useless.
Use live validation only where feedback during typing is the point:
- Character counters ("120 characters remaining").
- Password rules shown as a checklist that ticks off as the user satisfies each one.
- Username availability, with a delay (a debounce) so you do not query the server on every key.
For these, show progress rather than an error. A checklist that turns from "not met" to "met" tells the user what to do. A red error saying "Invalid password" after the first character does not.
A hybrid: reward early, punish late
A pattern that works well in practice combines the strategies by the state of the field:
- Before the user has interacted with a field, show nothing.
- When the user leaves the field, validate it. If it fails, show the error.
- Once a field is showing an error, re-validate on every
inputevent, so the error disappears as soon as the user fixes it. - On submit, validate everything, show all errors, and move focus to the first invalid field.
Step 3 is the important one. The trigger for showing an error is late (blur), but the trigger for removing it is early (typing). Users do not like staring at a red message after they have already corrected the problem.
Implementing the hybrid pattern
The code below builds on the approach from the earlier examples. It assumes <form novalidate> so the browser's own bubbles do not compete with your messages, and a <p id="email-error" hidden></p> after the input. It uses the Constraint Validation API, where each field exposes a validity object with flags such as valueMissing and typeMismatch.
const form = document.querySelector('form');
const email = document.getElementById('email');
// Fields that have already shown the user an error once.
const touched = new Set();
function messageFor(input) {
if (input.validity.valueMissing) {
return 'Enter your email address';
}
if (input.validity.typeMismatch) {
return 'Enter an email address in the format [email protected]';
}
return '';
}
function showError(input, message) {
const error = document.getElementById(input.id + '-error');
error.textContent = message;
error.hidden = !message;
if (message) {
input.setAttribute('aria-invalid', 'true');
input.setAttribute('aria-describedby', error.id);
} else {
input.removeAttribute('aria-invalid');
input.removeAttribute('aria-describedby');
}
}
// Show errors late: when the user leaves the field.
email.addEventListener('blur', () => {
const message = messageFor(email);
if (message) touched.add(email);
showError(email, message);
});
// Clear errors early: re-check while typing, but only after a first error.
email.addEventListener('input', () => {
if (touched.has(email)) {
showError(email, messageFor(email));
}
});
// Final gate: check everything on submit.
form.addEventListener('submit', (event) => {
if (!form.checkValidity()) {
event.preventDefault();
touched.add(email);
showError(email, messageFor(email));
form.querySelector(':invalid').focus();
}
});Notice three details.
- The
inputhandler runs only for fields intouched. A user typing into a fresh field never sees an error mid-word. - The same
messageForfunction serves all three events, so the wording never differs between them. - On a failed submit, focus moves to the first invalid field in document order, which is where the user should start fixing.
If your form has many fields, loop over them instead of naming each one. Keep one function that maps a field's validity to a message.
Edge cases
Empty optional fields
An optional field that is empty is valid. If you mark an optional phone field as invalid on blur because it is empty, you have contradicted your own "optional" label. Check format only when a value is present. For type="email" and pattern, the browser already treats an empty, non-required field as valid.
Autofill and paste
Browser autofill and paste can fill a field without the user typing in it. They fire input and change events in most browsers, but may not fire blur on every field. This is another reason the submit check must cover all fields.
Dependent fields
Some rules involve two fields, such as "confirm password" or "end date must be after start date". Validate the pair when the second field blurs, and re-validate the first if it changes later. Attach the error to the field the user needs to change.
Server-side validation
Client-side validation is a convenience, not a security measure. A user can bypass it, so the server must validate again. Some checks only the server can do, such as "this username is taken" or "this coupon has expired". Show those errors with the same pattern: a message linked to the field, focus on the first problem, and the user's input preserved. When the server returns errors, treat them the same as client-side ones so the user does not see two different styles.
Screen reader noise
Each time you change the text of an error element that is announced, a screen reader may speak it. Validation on every keystroke with a live region can produce a flood of speech. The hybrid pattern limits this: an error appears once on blur and updates only after that. Avoid putting aria-live on error messages that change on every keystroke. A later chapter covers accessible errors in detail.
Do not disable the submit button
A disabled submit button hides the reason a form cannot be sent. Keyboard and screen reader users may not be able to focus a disabled button at all, so they never learn what is wrong. Leave the button enabled, and when the user presses it, explain what needs fixing.
Choosing a strategy
Use these questions to decide.
- Is the field ever "complete" before the user leaves it? If not (email, postcode), do not validate while typing. Use blur.
- Does the user benefit from watching a value change? (counter, checklist, availability) If yes, give live progress, not errors.
- Is the form short? On a two-field form, submit-only validation can be enough.
- Is the check expensive or server-based? Run it on blur or after a pause, not on each key.
- Is the user likely to tab through? Wait until they have typed something, or until the first submit.
When unsure, use the hybrid pattern. It is the default that most often matches user expectations.
Common mistakes
- Validating on every keystroke from the first character.
- Showing all errors on page load, for example after a back-button return, before the user has done anything.
- Clearing an error only on the next blur, so a fixed field stays red.
- Using
placeholderor color changes alone to signal a problem. - Skipping the submit check because the blur checks "already caught everything".
- Disabling the submit button instead of explaining the problem.
Exercise
A user tabs into the "Postcode" field, types "SW1A", and presses Tab to move on. Using the hybrid pattern, when should the error for an incomplete postcode first appear, when should it disappear, and why should it not appear while the user types "S", "SW", and "SW1"?
Show answer
The error first appears on blur, when the user leaves the field with an invalid value. It disappears on the first input event after that where the value passes the rules, because the field is now in the touched state and is re-checked as the user types. It should not appear while typing "S", "SW", or "SW1" because the value is incomplete, not wrong. The user has not signaled they are finished, so an error would be accurate but unhelpful.
Exercise
Your form has an optional "Phone number" field with a pattern attribute. A user leaves it empty and tabs on. Should the blur handler show an error? What should happen if the user types "abc" and tabs on?
Show answer
No error for the empty field. An optional empty field is valid, and flagging it contradicts the "optional" label. For "abc", the value is present and fails the pattern, so the blur handler should show an error such as "Enter a phone number using digits only". The handler should check format only when a value is present.
Exercise
A teammate proposes disabling the "Create account" button until every field is valid, so no validation messages are needed. Give two reasons to reject this.
Show answer
First, a disabled button hides the cause. The user sees a button that will not respond and gets no explanation of which field is wrong. Second, disabled buttons are often skipped by keyboard focus and may not be announced to screen reader users, so they cannot discover why the form cannot be submitted. Leave the button enabled and show specific errors on press.