Tab Form Validation and State Management
Validation and state management for a multi-step form. Here is how to handle both.
Tab Form Validation and State Management
State Management
Use a single object for all form data:
const formData = { name: "", email: "", address: "", city: "", card: "", };
Update on every input:
function updateField(name, value) { formData[name] = value; }
This persists data across tabs because the object is not re-created.
Per-Step Validation
function validateStep(stepIndex) { const step = steps[stepIndex]; for (const field of step.fields) { if (field.required && !formData[field.name]) { showError(`${field.label} is required`); return false; } if (field.type === "email" && formData[field.name]) { if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData[field.name])) { showError("Invalid email"); return false; } } } return true; }
Prevent Skipping Unvalidated Steps
function goToStep(step) { // validate all steps before the target for (let i = 0; i < step; i++) { if (!validateStep(i)) { currentStep = i; // jump to the first invalid step renderStep(); return; } } currentStep = step; renderStep(); }
Progress Indicator
function updateProgress() { const progress = ((currentStep + 1) / steps.length) * 100; progressBar.style.width = progress + "%"; }
The Takeaway
State: single formData object, updated on every input. Validation: per-step, check required fields and format (email regex). Prevent skipping: validate all previous steps before jumping. Progress indicator: (currentStep + 1) / totalSteps * 100. This ensures data integrity and a good UX.
Use a single object for all form data: const formData = { name: '', email: '', address: '' }. Update on every input change. The object persists across steps because it is in the outer scope, not re-created on each render.
Check required fields and format. For each field in the current step: if required and empty, show error. If email, check regex. If invalid, prevent navigation. Return true only if all fields pass.
Before jumping to step N, validate all steps from 0 to N-1. If any is invalid, jump to the first invalid step and show the error. This ensures the user cannot skip to a later step without filling in required data.
Calculate: ((currentStep + 1) / steps.length) * 100. Set the progress bar width to this percentage. Update on every step change. This gives the user a visual indication of how far they are in the form.
Validate on step change (when the user tries to proceed). This is less intrusive. Optionally, show real-time validation (green checkmark for valid fields) but do not block until the user tries to move to the next step.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

