Forms, Validation & Browser Storage
Read form data, combine native and custom validation, and store small preferences without letting storage failures break the page.
By the end, you’ll be able to…
- Handle form submission and read named controls with FormData.
- Use HTML constraint validation and add a custom validity message.
- Store and retrieve JSON data with localStorage or sessionStorage.
- Handle quota and parsing failures and present accessible error messages.
01Submit is an event you control
A form exists to collect values and send them somewhere. When JavaScript handles the submission, listen for the submit event on the form, not click on the button. Call preventDefault to stop the browser's navigation, then read the data. Listening on the form also catches submission triggered by pressing Enter, which a click listener would miss.
FormData reads named controls into key-value pairs. Pass the form element and call get for a single value or getAll for repeated names such as checkboxes. FormData includes only controls with a name, so markup and script must agree. Convert numeric values explicitly with Number and validate before using them in calculations.
02Use and extend constraint validation
HTML can validate without JavaScript: required, type='email', minlength, min, max, and pattern. The form's checkValidity method reports whether all controls pass; reportValidity also shows the browser's messages and moves focus to the first problem. Native validation blocks the submit event for invalid forms, so a submit handler normally runs only after those checks pass. The novalidate attribute deliberately hands control to your own flow.
setCustomValidity attaches your own message to a control; call it with an empty string to clear the message. validationMessage gives the current text. Prefer the built-in checks for simple rules and add custom checks for relationships, such as matching passwords. Show errors next to the field and connect them with aria-describedby so the message is announced with the input.
03Storage with a small, clear API
localStorage stores strings for one origin and keeps them after the tab closes. sessionStorage behaves the same way but lasts only for the tab session. Both expose setItem, getItem, removeItem, and clear. Keys are strings; values must be strings too. Namespace keys with an application prefix to avoid collisions with other code on the same origin.
Objects need serialization. JSON.stringify converts a value to text, and JSON.parse turns stored text back into a value. Wrap parsing in try/catch because storage may contain old, corrupted, or hand-edited data. Treat stored data as untrusted input: check its shape and fall back to a safe default instead of assuming it matches today's schema.
04Limits, failures, and accessible feedback
Storage is not unlimited. Browsers impose per-origin quotas, often a few megabytes, and setItem can throw when the quota is exceeded. Private browsing or blocked site data can make storage unavailable and throw a SecurityError. Catch the failure and continue with in-memory state; a saved preference is a convenience, not a reason for the page to stop working.
Every input needs a visible label, not just a placeholder. Link error text with aria-describedby and use aria-live='polite' for a summary that changes after submission. On success, say what happened and move focus only when it helps. Keep error language specific: say which field needs attention and how to fix it, rather than displaying a generic failure banner.
The ideas worth keeping.
- Handle submit on the form, cancel navigation, and read named controls through FormData.
- Combine native constraints with custom validity messages, and connect errors to fields for assistive technology.
- Serialize objects with JSON, namespace storage keys, and handle quota, security, and parsing failures gracefully.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Validate a booking form
A form with id booking uses the novalidate attribute. On submit, prevent the default action, call reportValidity, and stop if it returns false. Otherwise build an object with name (trimmed text), guests (a number), and date from FormData, then log it.
Explore a worked solution
const form = document.querySelector("#booking");form.addEventListener("submit", (event) => { event.preventDefault(); if (!form.reportValidity()) return; const data = new FormData(form); const booking = { name: String(data.get("name")).trim(), guests: Number(data.get("guests")), date: String(data.get("date")) }; console.log("Booking", booking);});With novalidate, the submit event fires even when fields are invalid, so the script must ask the browser to show messages and stop. Explicit conversion keeps guests numeric for later calculations.
Exercise 2: Save and restore favourites
Write saveFavourites(items) that stores an array under 'coursepodia:favourites' as JSON, inside try/catch. Write loadFavourites() that reads the key, parses it, and returns the array only when every entry is a string; otherwise return an empty array. Do not let a storage error escape.
Explore a worked solution
const KEY = "coursepodia:favourites";function saveFavourites(items) { try { localStorage.setItem(KEY, JSON.stringify(items)); return true; } catch (error) { console.warn("Could not save favourites:", error); return false; }}function loadFavourites() { try { const raw = localStorage.getItem(KEY); const parsed = raw ? JSON.parse(raw) : []; return Array.isArray(parsed) && parsed.every((item) => typeof item === "string") ? parsed : []; } catch (error) { console.warn("Could not load favourites:", error); return []; }}Both functions convert a possible exception into a safe result. The loader checks the parsed shape, so stale or corrupted data cannot reach code that expects an array of strings.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Validate a booking form
A form with id booking uses the novalidate attribute. On submit, prevent the default action, call reportValidity, and stop if it returns false. Otherwise build an object with name (trimmed text), guests (a number), and date from FormData, then log it.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.