🧩 Step 1: Form Setup in React
Start with a simple form that collects user details like name, email, and password.
import React, { useState } from "react";
function Register() {
const [form, setForm] = useState({ name: "", email: "", password: "" });
const [error, setError] = useState("");
const [success, setSuccess] = useState("");
const handleChange = (e) => {
setForm({ ...form, [e.target.name]: e.target.value });
};
🧩 Step 2: Client-Side Validation
Before submitting, ensure required fields are filled and email/password follow rules.
const validate = () => {
if (!form.name || !form.email || !form.password) {
return "All fields are required.";
}
if (!/\S+@\S+\.\S+/.test(form.email)) {
return "Invalid email format.";
}
if (form.password.length < 6) {
return "Password must be at least 6 characters.";
}
return "";
};
🧩 Step 3: Handle Submission with Error Handling
Send validated data to the Node.js backend and handle success/failure.
const handleSubmit = async (e) => {
e.preventDefault();
const validationError = validate();
if (validationError) return setError(validationError);
try {
const res = await fetch("http://localhost:5000/api/register", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(form),
});
const data = await res.json();
if (!res.ok) throw new Error(data.message || "Something went wrong");
setSuccess("Registration successful!");
setForm({ name: "", email: "", password: "" });
setError("");
} catch (err) {
setError(err.message);
}
};
🧩 Step 4: Display Feedback
return (
<form onSubmit={handleSubmit}>
<input name="name" placeholder="Name" value={form.name} onChange={handleChange} />
<input name="email" placeholder="Email" value={form.email} onChange={handleChange} />
<input name="password" type="password" placeholder="Password" value={form.password} onChange={handleChange} />
<button type="submit">Register</button>
{error && <p style={{ color: "red" }}>{error}</p>}
{success && <p style={{ color: "green" }}>{success}</p>}
</form>
);
}
export default Register;
🧩 Step 5: Node.js Backend (Express Example)
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.post("/api/register", (req, res) => {
const { name, email, password } = req.body;
if (!name || !email || !password)
return res.status(400).json({ message: "All fields are required" });
// Simulate database save
console.log("User registered:", { name, email });
res.status(200).json({ message: "User registered successfully" });
});
app.listen(5000, () => console.log("Server running on port 5000"));
🧩 Step 6: Error Handling & Improvements
- Handle network errors gracefully (
try/catchin frontend). - Display clear messages for validation vs server errors.
- Add loading state during submission.
- Consider using Formik + Yup for scalable validation.
- Implement backend validation again to ensure security.
✅ Summary:
- Validate inputs on frontend (basic checks).
- Use
fetchoraxiosfor data submission. - Handle success/error responses gracefully.
- Re-validate on backend for data integrity.