Sequence NODE_200
MediumBuild a Simple Form with Validation Messages
React
JavaScript
Technical Specification
Create a signup form with name, email and password, showing simple validation messages before submit.
Input/Output Samples
Input:Empty email
Output:Shows 'Email is required'
Optimal Logic Path
import { useState } from "react";
function SignupForm() {
const [values, setValues] = useState({
name: "",
email: "",
password: ""
});
const [errors, setErrors] = useState({});
function handleChange(e) {
const { name, value } = e.target;
setValues((v) => ({ ...v, [name]: value }));
}
function handleSubmit(e) {
e.preventDefault();
const newErrors = {};
if (!values.name.trim()) newErrors.name = "Name is required";
if (!values.email.includes("@")) newErrors.email = "Valid email is required";
if (values.password.length < 6)
newErrors.password = "Password must be at least 6 characters";
setErrors(newErrors);
if (Object.keys(newErrors).length === 0) {
// submit logic
}
}
return (
<form onSubmit={handleSubmit}>
<div>
<input
name="name"
value={values.name}
onChange={handleChange}
placeholder="Name"
/>
{errors.name && <p>{errors.name}</p>}
</div>
<div>
<input
name="email"
value={values.email}
onChange={handleChange}
placeholder="Email"
/>
{errors.email && <p>{errors.email}</p>}
</div>
<div>
<input
name="password"
type="password"
value={values.password}
onChange={handleChange}
placeholder="Password"
/>
{errors.password && <p>{errors.password}</p>}
</div>
<button type="submit">Sign up</button>
</form>
);
}Architectural Deep-Dive
We compute an errors object on submit and only continue if there are no validation messages.