Part 05 / Topic 4 of 7
Validation on submit
Validating on every keystroke means showing a "required" error while the user has barely started typing their name - unpleasant, and not what this part's mini-build does. Validating on submit means a plain function that looks at the form's current state all at once, and returns an object describing what is wrong:
// examples/04_validation_on_submit.jsx
function validate(details) {
const errors = {};
if (!details.name.trim()) {
errors.name = "Name is required.";
}
if (!details.email.includes("@")) {
errors.email = "Enter a valid email address.";
}
return errors;
}
The submit handler calls it, stores the result in its own errors state, and only treats the submission as successful once that object comes back with no keys at all:
// examples/04_validation_on_submit.jsx
function handleSubmit(event) {
event.preventDefault();
const nextErrors = validate(details);
setErrors(nextErrors);
if (Object.keys(nextErrors).length === 0) {
setSubmittedMessage(`Account created for ${details.name}.`);
} else {
setSubmittedMessage("");
}
}
Each field renders its own error right underneath it, only when that key exists on errors: {errors.name && <p role="alert">{errors.name}</p>}. Submitting with an empty name and "not-an-email" typed into the email field really shows both messages at once, with the typed values still sitting in both inputs - validation never clears what was typed (examples/04_validation_on_submit.test.jsx). Filling in a real name and a real email and submitting again really clears both messages and shows "Account created for Rahul." - and fixing only the name while leaving the email broken really clears only the name's error on the next submit, because validate reruns from scratch and only ever returns keys for what is still actually wrong.
๐ Going deeper:
role="alert"on each error paragraph is not decoration - it is what lets a screen reader announce the message the moment it appears, without the user having to go looking for it. This course has not covered accessibility as its own topic yet, but a form's error messages are exactly the kind of UI where skipping it genuinely locks someone out.
Done here? The practice set for Part 5 โ including the solutions โ is on the part page.