What is the general flow for validating a form with per-field error messages?
Clear all old messages, validate each field (writing an error next to it on failure), then check whether any message was set — none means proceed, otherwise the user already sees what's wrong.
* The three-step validation flow — the final decision just checks whether step ② left any message behind. *
Form validation comes in two flavours that are usually combined: declarative constraints in the HTML (type="email", required, minlength, …) and programmatic checks in JavaScript (own rules on value). Whichever mix you use, the submit handler follows the same three-step flow:
- Clear current messages — empty every error element (e.g. a
<p class="error">under each input), so stale errors from the previous attempt disappear. - Validate each input field — via
checkValidity()+validationMessagefor declarative constraints, or your own checks onvalue; on failure, write the message into that field's error element. - Check whether any error occurred — e.g. test whether any error element is non-empty. No errors → proceed (send the data); errors → stop, the user is already informed inline.
function submitForm() {
clearValidationErrors(); // 1. wipe old messages
validateName(); // 2. each validator writes its
validateEmail(); // own message on failure
if (!hasValidationErrors()) { // 3. all clear?
// proceed, e.g. send the data
}
}
Why this shape: each validator stays independent (adding a field = adding one function), the error state lives visibly in the DOM right next to the offending field, and the final gate is one generic check instead of threading return values through every validator.
Go deeper:
Client-side form validation (MDN) — the full tutorial: built-in constraints, custom messages, and styling the error states.