javascript 65 lines · 10 steps

Building a validated signup form in React

A controlled React form that validates on blur and submit, showing errors only for fields the user has touched.

Explained by highlit
1import { useState } from "react";
2 
3const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
4 
5function validate({ email, password, confirm }) {
6 const errors = {};
7 if (!email.trim()) errors.email = "Email is required.";
8 else if (!EMAIL_RE.test(email)) errors.email = "Enter a valid email address.";
9 if (!password) errors.password = "Password is required.";
10 else if (password.length < 8) errors.password = "Must be at least 8 characters.";
11 if (confirm !== password) errors.confirm = "Passwords do not match.";
12 return errors;
13}
14 
15export default function SignupForm({ onSubmit }) {
16 const [values, setValues] = useState({ email: "", password: "", confirm: "" });
17 const [errors, setErrors] = useState({});
18 const [touched, setTouched] = useState({});
19 
20 const handleChange = (e) => {
21 const { name, value } = e.target;
22 setValues((prev) => ({ ...prev, [name]: value }));
23 };
24 
25 const handleBlur = (e) => {
26 const { name } = e.target;
27 setTouched((prev) => ({ ...prev, [name]: true }));
28 setErrors(validate({ ...values }));
29 };
30 
31 const handleSubmit = (e) => {
32 e.preventDefault();
33 const nextErrors = validate(values);
34 setErrors(nextErrors);
35 setTouched({ email: true, password: true, confirm: true });
36 if (Object.keys(nextErrors).length === 0) onSubmit(values);
37 };
38 
39 const fieldError = (name) => touched[name] && errors[name];
40 
41 return (
42 <form onSubmit={handleSubmit} noValidate>
43 {[
44 { name: "email", label: "Email", type: "email" },
45 { name: "password", label: "Password", type: "password" },
46 { name: "confirm", label: "Confirm password", type: "password" },
47 ].map(({ name, label, type }) => (
48 <div key={name} className="field">
49 <label htmlFor={name}>{label}</label>
50 <input
51 id={name}
52 name={name}
53 type={type}
54 value={values[name]}
55 onChange={handleChange}
56 onBlur={handleBlur}
57 aria-invalid={Boolean(fieldError(name))}
58 />
59 {fieldError(name) && <span className="error" role="alert">{errors[name]}</span>}
60 </div>
61 ))}
62 <button type="submit">Create account</button>
63 </form>
64 );
65}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Keeping validation in a pure function separate from the component makes rules easy to test and reuse.
  2. 2Tracking a 'touched' set lets you defer error messages until a field has actually been interacted with.
  3. 3Wiring aria-invalid and role='alert' turns visual validation into accessible feedback for free.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a validated signup form in React — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code