Form Validation

Last updated: 2026-11-02

Form Validation Form Validation

The essence of validation is deriving errors from state: a validation function computes an errors object, the whole object is checked once before submitting, and when something is wrong the submit is blocked and the message is rendered. Error messages are UI too, so conditional rendering is enough — no imperative DOM work is required. Because the errors are computed while rendering, they can never drift out of sync with the fields they describe, which removes a whole class of stale-message bugs.

GroupComponent Patterns
KindPattern

ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.

📝 Syntax

const errors = validate(values)   // derive errors from state
const hasError = Object.keys(errors).length > 0

<form onSubmit={e => {
  e.preventDefault()               // block the browser default submit
  if (!hasError) submit(values)
}}>

Returns:No return value; this entry describes an encoding pattern rather than a function.

▶ Example

The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.

Output:

When the email is missing an @ or the password is shorter than 6 characters, clicking "Register" shows a red error under the matching field; once both are valid the page shows "Registered successfully".

💡 Key Points

💡 Tip Touch first, complain later: a touched or submitted flag controls when errors appear, so the user never faces a wall of red text on arrival.
ℹ️ Info Derive errors during render instead of storing them with setState — derivation guarantees they stay in sync with the input.
⚠️ Warning Forgetting preventDefault lets the form run the browser native submit and reload the page, so the error messages flash by and vanish.
More case studies coming soon.

📚 Related Tutorials

❓ FAQ

Q Should validation live in onChange or onSubmit?
A Put the critical format checks in one place at submit time; friendly live hints can live in onChange or onBlur — the two do not conflict.
Q Should error messages be stored in state?
A Not recommended. Errors are a derivation of state, so compute them while rendering; storing them can leave them out of sync with the input.
Q Why do errors not show up after submitting?
A Common causes: onSubmit forgot e.preventDefault() so the page was submitted natively and reloaded, or the flag the error display depends on was never set.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏