React
Controlled Form with Validation
Build a controlled React form with inline validation and error messages.
By EZ4Code Team
formvalidationintermediate
Code
import { useState } from "react";
function ContactForm() {
const [form, setForm] = useState({ name: "", email: "", message: "" });
const [errors, setErrors] = useState({});
const validate = () => {
const e = {};
if (!form.name) e.name = "Name is required";
if (!/\S+@\S+/.test(form.email)) e.email = "Invalid email";
setErrors(e);
return Object.keys(e).length === 0;
};
const handleSubmit = (e) => {
e.preventDefault();
if (validate()) {
console.log("Submitted:", form);
}
};
return (
<form onSubmit={handleSubmit}>
<input
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
/>
{errors.name && <span>{errors.name}</span>}
<button type="submit">Send</button>
</form>
);
}Explanation
Implements a controlled form where input values are bound to useState and updated via onChange. The validate function checks required fields and email format, storing errors in state for inline display. Validation runs on submit, and errors only clear when the user corrects the input.