4. Interactive Apps, Storage & APIs
Form Validation & Browser Storage (localStorage)
Build friendly JavaScript form validation with clear inline errors and persist user data across page reloads using JSON and browser localStorage.
- Validate user input cleanly in JavaScript and display helpful inline error feedback
- Store and retrieve structured arrays and objects in localStorage using JSON
- Guard JSON.parse() safely against empty or corrupted browser storage
Have you ever filled out a checklist or preference toggle on a website, refreshed the tab, and groaned when everything reset back to zero? Without persistence, JavaScript variables disappear the instant a browser tab closes or refreshes.
Two essential frontend skills solve this cleanly: thoughtful client-side validation before accepting input, and browser storage (localStorage) to remember user data across visits without needing a backend server.
Friendly JavaScript Form Validation
HTML attributes like required and type="email" catch basic omissions, yet custom JavaScript validation lets you enforce richer business rules and display consistent inline error messages right beside the input:
const form = document.querySelector("#goal-form");
const goalInput = document.querySelector("#goal-input");
const errorEl = document.querySelector("#goal-error");
form.addEventListener("submit", (event) => {
event.preventDefault();
const value = goalInput.value.trim();
if (value.length < 3) {
errorEl.textContent = "Please enter at least 3 characters for your study goal.";
goalInput.focus();
return;
}
errorEl.textContent = "";
saveGoal(value);
goalInput.value = "";
});Notice .trim() right before checking .length: trimming whitespace prevents someone from accidentally submitting " " (three blank spaces).
Remembering State Across Refresh with localStorage
Every domain (such as yadavacademy.com) gets a small, fast key-value storage locker right inside the user's browser called localStorage. Values saved there survive page refreshes and even closing/reopening the browser!
| Method | Purpose | Example |
|---|---|---|
localStorage.setItem(key, str) | Save a string under key | localStorage.setItem("theme", "light") |
localStorage.getItem(key) | Read saved string (returns null if missing) | localStorage.getItem("theme") |
localStorage.removeItem(key) | Delete one saved key | localStorage.removeItem("draft") |
localStorage.clear() | Wipe every key stored for this site | Use sparingly for "Reset App" buttons |
The Catch: localStorage Only Stores Text Strings!
If you pass an array ["HTML", "CSS"] straight into localStorage.setItem("tags", ["HTML", "CSS"]), JavaScript converts it into plain flattened text "HTML,CSS", stripping away array structure and objects!
To preserve arrays and objects faithfully, serialize them with JSON.stringify() on the way in, and restore them with JSON.parse() on the way out:
const STORAGE_KEY = "study-goals-v1";
// 1. Save array of objects cleanly as JSON text
function saveGoals(goals) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(goals));
}
// 2. Load safely with a try/catch fallback
function loadGoals() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
return raw ? JSON.parse(raw) : [];
} catch {
return []; // Fallback safely if browser storage was corrupted
}
}Any JavaScript running on your domain can read localStorage immediately. Use localStorage for UI preferences, study progress, cart drafts, and non-sensitive caches—never for private passwords, credit cards, or secret API keys.
Try It Live: Inline Validation & Saved Draft State
Try submitting an empty or short goal to test the inline validation error, then save valid goals below:
Quick Checkpoints
Why do developers wrap arrays and objects in JSON.stringify(...) before saving them to localStorage?
What should you call on user input strings before checking .length in form validation?