sr✳SHUBHAM RAJFRONTEND ENGINEER
FULL TECHNICAL GUIDEFoundation3 min read

Where should form validation happen?

Use browser constraints and client validation for fast feedback, then validate every submitted value again on the server.

React#forms#validation
THE ANSWER / PLAIN ENGLISH

The idea to remember.

Use browser constraints and client validation for fast feedback, then validate every submitted value again on the server. Client checks alone cannot enforce security or data integrity.

From first example to real project.

Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.

Basic: controlled input

01 / BEGINNER

Keep the visible value in React state.

JSX / EXAMPLE
function NameField() {
  const [name, setName] = React.useState('');
  return <input value={name} onChange={e => setName(e.target.value)} />;
}

Intermediate: validate on submit

02 / INTERMEDIATE

Use built-in form semantics and show actionable errors.

JSX / EXAMPLE
function Signup() {
  function submit(e) {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    if (!String(data.get('email')).includes('@')) return;
    // Send validated form data to the server.
  }
  return <form onSubmit={submit}><label>Email <input name="email" type="email" required /></label><button>Join</button></form>;
}

Real scenario: save safely

03 / REAL SCENARIO

Disable duplicate submissions, surface failures and preserve input.

JSX / EXAMPLE
async function submitProfile(formData, setSaving, setError) {
  setSaving(true);
  setError('');
  try {
    const response = await fetch('/api/profile', { method: 'POST', body: formData });
    if (!response.ok) throw new Error('Could not save');
  } catch (error) { setError(error.message); }
  finally { setSaving(false); }
}

Try it in your own words.

Explain where should form validation happen without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.

Keep learning here.

Explore more in-depth guides, exercises and related interview questions in this library.

Browse React study guides ↗
← Back to question library

Have something
in mind?

Start a conversation