Sub topic 4
Validation rules and when to run them
This chapter assumes you know basic HTML form elements, can read TypeScript, and understand how a browser submits form data. It builds on the previous chapter, which covered form state: values, touched, dirty, and errors. Here you decide which rules to enforce and when to show their results.
Two questions, not one
Validation answers two separate questions.
- What counts as valid? These are the rules: required, format, range, cross-field consistency, and uniqueness.
- When do you check and when do you show the result? This is the timing: on input, on blur, on step change, or on submit.
Teams often mix these up and end up with a form that shows "Invalid email" while the user is still typing the second character. Keep the two decisions apart. You can run a rule at any moment and still choose to show its result later.
Kinds of rules
Rules differ in how much they cost to check and where they must run.
| Rule type | Example | Where it can run |
|---|---|---|
| Presence | Name is required | Client and server |
| Format | Email contains `@` and a domain | Client and server |
| Range or length | Age between 18 and 120 | Client and server |
| Cross-field | End date is after start date | Client and server |
| Remote | Username is not taken | Server only, called from the client |
| Business | Coupon is still active | Server only |
Client-side validation exists for speed and guidance. It is not a security control. A user can bypass it, so the server must re-check every rule that matters. Treat the client rules as a courtesy that saves a round trip.
Use the browser's built-in constraints first
HTML gives you required, type, min, max, minlength, maxlength, and pattern. These work without JavaScript and expose input.validity and input.validationMessage. They are a good baseline. Their default bubbles are inconsistent across browsers and hard to style, so many teams add novalidate to the form and render their own messages while still reading validity for the logic.
<form novalidate>
<label for="age">Age</label>
<input id="age" name="age" type="number" min="18" max="120" required>
<button type="submit">Continue</button>
</form>With novalidate, the browser no longer blocks submission. Your code must now do that, so make sure it does. A form that has novalidate and no script check will submit anything.
Rules as data
Write each rule as a small pure function that returns an error message or nothing. Pure functions are easy to test and can be shared between steps.
type Values = Record<string, string>;
type Rule = (value: string, values: Values) => string | null;
const required =
(message: string): Rule =>
(value) =>
value.trim() === "" ? message : null;
const emailFormat: Rule = (value) =>
value === "" || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
? null
: "Enter an email address in the format [email protected].";
const matchesField =
(other: string, message: string): Rule =>
(value, values) =>
value === values[other] ? null : message;
const schema: Record<string, Rule[]> = {
email: [required("Enter your email address."), emailFormat],
confirmEmail: [matchesField("email", "The two email addresses do not match.")],
};
function validateField(name: string, values: Values): string | null {
for (const rule of schema[name] ?? []) {
const message = rule(values[name] ?? "", values);
if (message) return message;
}
return null;
}
function validateAll(values: Values): Record<string, string> {
const errors: Record<string, string> = {};
for (const name of Object.keys(schema)) {
const message = validateField(name, values);
if (message) errors[name] = message;
}
return errors;
}Two design choices are worth noting. First, validateField returns only the first failing message. Showing one problem at a time keeps the interface calm, and fixing it reveals the next. Second, emailFormat passes an empty value, because emptiness belongs to the required rule. Each rule should check one thing, so the user never sees "Enter an email" and "Invalid format" for the same empty field.
The email regex is deliberately loose. A strict pattern rejects real addresses. The only reliable proof an address works is sending a message to it.
When to run validation
There are four common trigger points. Each has a typical failure mode.
| Trigger | Benefit | Common failure |
|---|---|---|
| On input (every keystroke) | Immediate feedback | Errors appear before the user finishes typing |
| On blur (leaving the field) | Feedback after the user finishes | The user may never leave a field before clicking Submit |
| On step change | Limits errors to the current step | Errors in earlier steps stay unseen if the user jumps around |
| On submit | Catches everything | Feedback arrives late, after the user has done all the work |
The "reward early, punish late" pattern
A widely used compromise has two phases per field.
- Before the first error: stay quiet while the user types. Validate on blur.
- After a field has shown an error: validate on every input, so the message disappears the moment the value becomes valid.
This avoids interrupting someone mid-word, and it removes a stale error immediately once the user fixes it. Nothing is more irritating than a red message that remains after you have corrected the problem and have to click elsewhere to clear it.
This is where the touched flag from the previous chapter earns its place. An error is displayed only when the field is touched or a submit was attempted.
type FieldState = {
value: string;
touched: boolean;
error: string | null;
};
type FormState = {
fields: Record<string, FieldState>;
submitAttempted: boolean;
};
function visibleError(state: FormState, name: string): string | null {
const field = state.fields[name];
if (!field) return null;
return field.touched || state.submitAttempted ? field.error : null;
}
function onInput(state: FormState, name: string, value: string): FormState {
const current = state.fields[name];
const values = Object.fromEntries(
Object.entries(state.fields).map(([key, f]) => [key, f.value])
);
values[name] = value;
// Re-validate on input only if an error is already showing.
const showingError = visibleError(state, name) !== null;
const error = showingError ? validateField(name, values) : current.error;
return {
...state,
fields: { ...state.fields, [name]: { ...current, value, error } },
};
}
function onBlur(state: FormState, name: string): FormState {
const current = state.fields[name];
const values = Object.fromEntries(
Object.entries(state.fields).map(([key, f]) => [key, f.value])
);
return {
...state,
fields: {
...state.fields,
[name]: { ...current, touched: true, error: validateField(name, values) },
},
};
}This code reuses validateField and the schema from the earlier example, so keep them in the same module when you run it. The store keeps the computed error separate from the decision to display it, which is the point made at the start of the chapter.
Exceptions to the default
Some fields deserve different timing.
- Password strength and character counters help while typing. Show them live as guidance, not as errors.
- Formats with an obvious end, such as a card number, can validate once the expected length is reached.
- Remote checks, such as username availability, should be debounced and run on blur or after a pause of a few hundred milliseconds. Do not call the server on every keystroke.
- Dependent fields need re-validation when their partner changes. If
confirmEmailmatchesemail, editingemailmust re-run the rule forconfirmEmail, or a stale error or a stale pass remains.
Remote validation and race conditions
Asynchronous checks can return out of order. If the user types ann, then anna, and the response for ann arrives last, the form shows the result for the wrong value. Guard against this by checking that the value you validated is still the current value.
const latest: Record<string, number> = {};
async function checkUsername(
value: string,
isTaken: (name: string) => Promise<boolean>,
current: () => string
): Promise<string | null> {
const ticket = (latest.username = (latest.username ?? 0) + 1);
const taken = await isTaken(value);
if (ticket !== latest.username || value !== current()) return null; // stale
return taken ? "That username is taken. Try another." : null;
}A return value of null for a stale response means "no new information", so the caller must not overwrite the existing state with it. Handle that case explicitly. Also decide what happens if the network call fails. Usually the answer is to let the user continue and rely on the server check at submit, because blocking progress on a failed courtesy check is worse than a late error.
Validation across steps
In a multi-step flow, add two rules.
- Validate the current step's fields before moving forward. Moving back should never require validity, so users can leave and fix earlier answers.
- Re-validate everything at the final submit. A value from step one may be affected by a change made in step three, such as a country change that alters the valid postal code format. Do not trust that earlier steps are still valid.
Only validate fields that are visible. A hidden field's rules must not block the user, and its value must not be submitted. The conditional-fields chapter covers this in detail.
Skip the diagram syntax above; use the following diagram instead.
Common errors
- Validating on input from the first keystroke. The user sees errors for values they have not finished typing.
- Clearing errors only on blur. A corrected field still looks wrong.
- Forgetting dependent fields. Matching, range, and date rules go stale when the other field changes.
- Validating hidden fields. The user is blocked by a field they cannot see.
- Trusting the client. Every rule that protects data must run on the server too.
- Disabling the submit button until the form is valid. The user gets no explanation for why they cannot continue. Keep the button enabled, validate on click, and move focus to the first error.
- Blocking on a failed remote check. A network failure in a courtesy check should not stop the user.
Decision criteria
Use these questions to choose a timing for a new field.
- Is the rule cheap and local? Run it on blur, then on input once an error shows.
- Does it need the network? Debounce it, guard against stale responses, and always repeat it on the server.
- Does the user benefit from guidance while typing, as with password strength? Show a live hint, not an error.
- Does the field depend on another field? Re-run it whenever either changes.
- Is the field in an earlier step? Re-run it at final submit.
Exercise
A user fills in "Password" and "Confirm password". They type a matching pair, click Continue, then go back and change "Password" without touching "Confirm password". What must your validation do so the form stays correct, and when should an error appear?
Show answer
Changing "Password" must re-run the match rule for "Confirm password", because that rule depends on both values. Run it on the change of either field. Show the mismatch error only if "Confirm password" is already touched or a submit was attempted, so a user who has not yet reached that field is not shown an error early. Re-validate both fields again at final submit, since the step that contains them may have been passed with the older values.
Exercise
Why is it a bad idea to disable the Submit button until every field is valid, and what should you do instead?
Show answer
A disabled button gives no reason for being disabled, which leaves keyboard and screen reader users unable to learn what is wrong. Keep the button enabled. On click, run all validation for the visible fields, show the errors, and move focus to the first invalid field or to an error summary.