Command Palette

Search for a command to run...

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

The browser's own constraint validation

The first requestSubmit does nothing visible in the console: the browser found an empty required field and stopped before the submit event. Press Send yourself with empty fields to see the browser's bubble. :user-invalid styles a field only after the user has interacted with it.

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?

The browser's own constraint validation

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

form valid? false | email empty? true
type mismatch? true
onSubmit ran with asha@example.com