Build a Form Wizard in Vanilla JavaScript
Build a multi-step form wizard in vanilla JavaScript with per-step validation, a progress indicator, back and next buttons, saved answers and accessible focus.

Long forms put people off, and splitting them into steps is a well-known remedy. A form wizard shows a few fields at a time, checks each step before moving on and ends with a review and a submit. The hard parts are not the buttons. They are validating only the current step, keeping the answers when the user goes back, telling people where they are and managing focus so a keyboard or screen reader user is not left behind when the visible step changes. This post builds a form wizard in vanilla JavaScript on top of one ordinary <form>: the markup, the step controller, per-step validation using the browser's constraint API, a progress indicator, focus handling, saving the draft and a final submit. Because it is a real form, it still works for the basics without script. The validation API is documented on MDN.
One form, several steps
Do not build a separate form per step. Keep a single <form> with each step as a <fieldset> inside it. That way the browser collects all the values on submit, the field names stay in one place and the markup is understandable without script.
<form id="wizard" novalidate>
<h1>Create account</h1>
<ol id="progress" aria-label="Progress">
<li>Account</li>
<li>Profile</li>
<li>Review</li>
</ol>
<fieldset data-step>
<legend>Account</legend>
<label>Email <input type="email" name="email" required autocomplete="email"></label>
<label>Password <input type="password" name="password" required minlength="8" autocomplete="new-password"></label>
</fieldset>
<fieldset data-step>
<legend>Profile</legend>
<label>Name <input type="text" name="name" required autocomplete="name"></label>
<label>Country
<select name="country" required>
<option value="">Choose…</option>
<option>Canada</option>
<option>Portugal</option>
<option>Japan</option>
</select>
</label>
</fieldset>
<fieldset data-step>
<legend>Review</legend>
<dl id="summary"></dl>
<label><input type="checkbox" name="terms" required> I agree to the terms</label>
</fieldset>
<p id="error" role="alert"></p>
<div class="actions">
<button type="button" id="back">Back</button>
<button type="button" id="next">Next</button>
<button type="submit" id="submit">Create account</button>
</div>
</form>
<script type="module" src="wizard.js"></script>(three fieldsets stacked in the markup; script will show one at a time)The form has novalidate, which turns off the browser's automatic bubbles on submit, so the script can validate step by step and show its own messages. The constraints themselves, required, type="email" and minlength, stay in the markup and keep working through the Constraint Validation API. The progress list is an ordered list, since it is a sequence.
The step controller
The controller tracks the current step and shows only that fieldset. Hide the others with the hidden attribute, which removes them from the accessibility tree and from the tab order, and disable their controls so they are not validated or submitted twice.
const form = document.querySelector("#wizard");
const steps = [...form.querySelectorAll("[data-step]")];
const progressItems = [...document.querySelectorAll("#progress li")];
const backButton = document.querySelector("#back");
const nextButton = document.querySelector("#next");
const submitButton = document.querySelector("#submit");
const errorEl = document.querySelector("#error");
let current = 0;
function showStep(index) {
current = index;
steps.forEach((step, i) => {
step.hidden = i !== index;
});
progressItems.forEach((item, i) => {
if (i === index) item.setAttribute("aria-current", "step");
else item.removeAttribute("aria-current");
item.classList.toggle("done", i < index);
});
backButton.hidden = index === 0;
nextButton.hidden = index === steps.length - 1;
submitButton.hidden = index !== steps.length - 1;
errorEl.textContent = "";
if (index === steps.length - 1) renderSummary();
const heading = steps[index].querySelector("legend");
heading.tabIndex = -1;
heading.focus();
}
showStep(0);
console.log(steps.length, backButton.hidden, submitButton.hidden);3 true trueAfter the step changes, focus moves to the new step's legend, which has tabindex="-1" so it can take focus without joining the tab order. Without this, a keyboard user pressing Next would find focus on a button that has just disappeared, and a screen reader user would hear nothing. The aria-current="step" attribute marks the active item in the progress list.
Validate only the current step
The Constraint Validation API makes this short. Each field has checkValidity() and a validationMessage. Loop through the fields in the current step and report the first problem.
function validateStep(index) {
const fields = [...steps[index].querySelectorAll("input, select, textarea")];
for (const field of fields) {
if (!field.checkValidity()) {
field.setAttribute("aria-invalid", "true");
errorEl.textContent = `${labelFor(field)}: ${field.validationMessage}`;
field.focus();
return false;
}
field.removeAttribute("aria-invalid");
}
errorEl.textContent = "";
return true;
}
function labelFor(field) {
const label = field.closest("label");
return label ? label.firstChild.textContent.trim() : field.name;
}
nextButton.addEventListener("click", () => {
if (validateStep(current)) showStep(current + 1);
});
backButton.addEventListener("click", () => showStep(current - 1));
console.log(typeof validateStep);functionThe error text uses the browser's own validationMessage, which is localized, such as "Please fill out this field." The message goes into an element with role="alert", so a screen reader announces it, and focus moves to the invalid field so the user can fix it. Going back never validates, because the user should always be free to return to an earlier step. Custom rules plug into the same mechanism: call field.setCustomValidity("Passwords must contain a number") and checkValidity() returns false until you clear it with setCustomValidity("").
const password = form.elements.password;
password.addEventListener("input", () => {
const hasNumber = /\d/.test(password.value);
password.setCustomValidity(hasNumber ? "" : "Include at least one number.");
});
password.value = "abcdefgh";
password.dispatchEvent(new Event("input"));
console.log(password.validationMessage);Include at least one number.Show progress
The progress list needs styling that shows the done, current and upcoming states without relying on color alone. A check mark and bold text help.
#progress { display: flex; gap: 1rem; list-style: none; padding: 0; counter-reset: step; }
#progress li { counter-increment: step; color: #666; }
#progress li::before { content: counter(step) ". "; }
#progress li.done::before { content: "✓ "; }
#progress li[aria-current="step"] { color: inherit; font-weight: 700; }
[data-step] { border: 0; padding: 0; margin: 0 0 1rem; }
[aria-invalid="true"] { outline: 2px solid #b00020; }(steps appear as "1. Account 2. Profile 3. Review"; finished steps show a check mark)The review step
On the last step, display what the user entered so they can check it. Read the values from the form with FormData and write them with textContent.
function renderSummary() {
const data = new FormData(form);
const summary = document.querySelector("#summary");
summary.replaceChildren();
const rows = [
["Email", data.get("email")],
["Name", data.get("name")],
["Country", data.get("country")],
];
for (const [label, value] of rows) {
const dt = document.createElement("dt");
const dd = document.createElement("dd");
dt.textContent = label;
dd.textContent = value;
summary.append(dt, dd);
}
}Email: [email protected]
Name: Ada
Country: PortugalThe password is deliberately left out of the summary. Add a button next to each row that jumps back to the step holding that field, which is a helpful convenience that costs one call to showStep.
Save the draft
If the form is long, save answers as the user goes, so an accidental reload does not lose them. Never store the password.
const KEY = "wizard-draft";
function saveDraft() {
const data = Object.fromEntries(new FormData(form));
delete data.password;
try {
sessionStorage.setItem(KEY, JSON.stringify({ data, step: current }));
} catch {
// storage unavailable
}
}
function restoreDraft() {
try {
const saved = JSON.parse(sessionStorage.getItem(KEY));
if (!saved) return;
for (const [name, value] of Object.entries(saved.data)) {
const field = form.elements[name];
if (field && field.type !== "checkbox") field.value = value;
}
showStep(Math.min(saved.step, steps.length - 1));
} catch {
// ignore a broken draft
}
}
form.addEventListener("input", saveDraft);
restoreDraft();(after a reload the name, email and country are filled in and the same step is shown)sessionStorage lasts for the browser tab, which suits a draft containing personal data. Use localStorage only if the user expects the draft to survive closing the tab, and say so.
Submit
The final submit validates every step again, in case a field changed or the user skipped ahead with the keyboard, and then sends the data.
form.addEventListener("submit", async (event) => {
event.preventDefault();
for (let i = 0; i < steps.length; i++) {
if (!validateStep(i)) {
showStep(i);
validateStep(i);
return;
}
}
submitButton.disabled = true;
try {
const response = await fetch("/api/accounts", { method: "POST", body: new FormData(form) });
if (!response.ok) throw new Error(`Status ${response.status}`);
form.replaceChildren(Object.assign(document.createElement("p"), { textContent: "Account created." }));
} catch (error) {
errorEl.textContent = "Something went wrong. Please try again.";
submitButton.disabled = false;
}
});(invalid data sends the user to the step with the problem; success replaces the form with a message)Validating every step again on submit is important. The server must validate as well, because client-side checks are a convenience and anyone can bypass them.
Practical notes
Keep steps short, with three to five fields each, and tell people how many there are before they start. Use the right type and autocomplete values so mobile keyboards and password managers help. Let users go back without losing data, which this design does by never clearing fields. Update the page title or announce the step change so screen reader users know where they are. Test the whole flow with the keyboard alone and with a screen reader, and test submitting with JavaScript errors in mind: if the script fails, the single form should still submit with the browser's own validation, which is one reason to keep one form rather than many.
Testing the wizard
Run through the form as three different users. The first fills in everything correctly and presses Next and Submit, which should work without a single message. The second leaves each step empty and presses Next, and should see the first problem on that step with focus on the field. The third fills in a step, goes forward, goes back and checks that nothing was lost. Then use only the keyboard, including the Back button and the progress list, and a screen reader to confirm that each step change is announced through the focus move to the legend.
Also test the browser features people rely on: a password manager should fill the account step because the autocomplete values are set, the browser's autofill should fill the name and country, and pressing Enter in a text field should behave sensibly. In this design, Enter inside a step submits the form, and the submit handler validates every step, so it takes the user to the first invalid step. If you prefer Enter to move to the next step, listen for the key on the form and call the next button's logic when the current step is not the last.
Last, disable JavaScript and look at the page. The three fieldsets are all visible, novalidate is still there and the form submits to the server. Remove novalidate from the markup and add it from script to keep that fallback useful.


