Forms, localStorage, Fetch and JSON in JavaScript: Validation, Theme Toggle, Loading Data and Error Handling
Form Validation
The browser's built-in checks (required, type="email") are a good start. You can add friendly custom messages with JavaScript. Always validate again on the server, because browser checks can be bypassed.
javascript
function validateEmail(v) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
}
function validateForm(data) {
const errors = {};
if (data.name.trim().length < 2) errors.name = "Enter your name (at least 2 letters).";
if (!validateEmail(data.email)) errors.email = "Enter a valid email like name@example.com.";
if (data.message.trim().length < 10) errors.message = "Write at least 10 characters.";
return errors;
}
console.log(JSON.stringify(validateForm({ name: "A", email: "bad", message: "short" })));
console.log(JSON.stringify(validateForm({ name: "Asha", email: "asha@example.com", message: "Please call me tomorrow." })));
Result
{"name":"Enter your name (at least 2 letters).","email":"Enter a valid email like name@example.com.","message":"Write at least 10 characters."} | {}
An empty object {} means no errors. In the page, show each message next to its field and set aria-invalid="true" on the bad input.
Show Errors Accessibly
javascript
form.addEventListener("submit", (e) => {
const data = Object.fromEntries(new FormData(form));
const errors = validateForm(data);
document.querySelectorAll(".error").forEach((el) => (el.textContent = ""));
if (Object.keys(errors).length) {
e.preventDefault(); // stop sending
for (const [field, message] of Object.entries(errors)) {
document.querySelector("#" + field + "-error").textContent = message;
document.querySelector("#" + field).setAttribute("aria-invalid", "true");
}
}
});
localStorage: Remember a Choice
javascript
const root = document.documentElement;
const saved = localStorage.getItem("theme");
if (saved) root.dataset.theme = saved;
document.getElementById("theme").addEventListener("click", () => {
const next = root.dataset.theme === "dark" ? "light" : "dark";
root.dataset.theme = next;
localStorage.setItem("theme", next);
});
We tested this in a DOM test environment: the first click set the theme to dark and saved it, the second click set it to light and saved it.
Result
theme: dark saved: dark | theme: light saved: light
Use data attributes With [data-theme="dark"] { --bg: #12141a; } in your CSS, one attribute switches the whole theme.
Never store secrets localStorage is readable by any script on the page. Do not store passwords or private data in it.
fetch, async and await
javascript
async function loadCakes(fetchFn) {
const res = await fetchFn("/api/cakes.json");
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
}
async function main() {
const okFetch = async () => ({ ok: true, json: async () => [{ name: "Mango" }] });
const badFetch = async () => ({ ok: false, status: 404 });
console.log("loaded:", JSON.stringify(await loadCakes(okFetch)));
try {
await loadCakes(badFetch);
} catch (e) {
console.log("error:", e.message);
}
}
main();
Result
loaded: [{"name":"Mango"}] | error: HTTP 404
In real code you pass the browser's own fetch: loadCakes(fetch). We used small fake functions here so the example runs anywhere. Always check res.ok because fetch does not throw on a 404 by itself.
Show Data Safely
javascript
const list = document.querySelector("#cakes");
for (const cake of cakes) {
const li = document.createElement("li");
li.textContent = cake.name; // textContent keeps it safe
list.append(li);
}
Practice
- Add validation to your contact form with messages beside each field
- Save a dark mode choice and apply it on page load
- Load a JSON file and show it as a list, with a message if loading fails
Conclusion
Validate forms with friendly messages, store small preferences in localStorage and load data with fetch plus clear error handling.
Quick Summary: Validation; accessible errors; localStorage; fetch; safe display.