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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Keeping validation in a pure function separate from the component makes rules easy to test and reuse.
- 2Tracking a 'touched' set lets you defer error messages until a field has actually been interacted with.
- 3Wiring aria-invalid and role='alert' turns visual validation into accessible feedback for free.
Related explainers
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
javascript
class HistoryStack { constructor(initial = '', limit = 100) { this.past = []; this.present = initial;
Building an undo/redo history stack
undo-redo
state-management
debouncing
Intermediate
7 steps
javascript
import { useState, useCallback, useRef } from 'react'; function LikeButton({ postId, initialLiked, initialCount }) { const [liked, setLiked] = useState(initialLiked);
Optimistic like button with React
optimistic-ui
abortcontroller
error-handling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-validated-signup-form-in-react-explained-javascript-3b38/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.