Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.6 — Validation and Error Messages
React · Example 1 of 2

Validate on blur and on submit, with accessible errors

An empty submit was sent from code: every error shows, the email field is marked invalid and linked to its message, and focus moved to it. Now type: each message updates live, because errors are worked out from the values on every render.

Validate with one function that turns values into errors, decide when to show them (on submit, on blur with a touched flag, or on change), connect each message to its field with aria-invalid and aria-describedby, use the browser's built-in checks where they fit, and always validate again on the server.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a validate function for a contact form with name (required) and message (at least 10 characters), and show each error under its field after the first submit.

02

Add aria-invalid and aria-describedby to a single username field that must be 3–15 characters, showing the error after the field is blurred.

Explain it without notes

01

Compare validating on submit, on blur and on change. Which would you choose and why?

02

Why derive errors from values instead of storing them in state?

03

How do you make an error message accessible?

04

How does native constraint validation interact with onSubmit, and what does noValidate change?

05

Why must the server validate again?

Validate on blur and on submit, with accessible errors

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

blocked: { email: 'Enter your email.', password: 'Use at least 8 characters.' }
aria-invalid: true
described by its message: Enter your email.
focused: email