DOM, Events and Forms · Lesson 36 of 40
Form Handling and Validation in JavaScript
Sign-up, login, checkout, contact, search – forms are how users give your app data. Handling them well means reading values correctly, validating before submission, showing helpful errors that everyone (including screen-reader users) can understand, and submitting without a jarring page reload. HTML does a lot of this for free; JavaScript fills the gaps.
In this lesson
- Built-in HTML validation attributes
- Reading values with
FormData - The Constraint Validation API and custom rules
- Accessible error messages and submitting with fetch
Start with HTML validation
<form id="signup" novalidate>
<label for="name">Full name</label>
<input id="name" name="name" required minlength="2" autocomplete="name">
<p class="error" id="name-error" aria-live="polite"></p>
<label for="email">Email</label>
<input id="email" name="email" type="email" required autocomplete="email">
<p class="error" id="email-error" aria-live="polite"></p>
<label for="phone">Mobile</label>
<input id="phone" name="phone" type="tel" pattern="[6-9][0-9]{9}" inputmode="numeric">
<p class="error" id="phone-error" aria-live="polite"></p>
<label for="password">Password</label>
<input id="password" name="password" type="password" required minlength="8" autocomplete="new-password">
<p class="error" id="password-error" aria-live="polite"></p>
<label><input type="checkbox" name="terms" required> I accept the terms</label>
<button type="submit">Create account</button>
</form>
Attributes such as required, type="email", minlength, pattern, min/max let the browser validate for you. novalidate on the form turns off the browser's own pop-up bubbles so you can show your own styled messages – while still using the browser's validation logic through JavaScript.
Reading values with FormData
const form = document.querySelector("#signup");
form.addEventListener("submit", (event) => {
event.preventDefault();
const data = new FormData(form); // every field with a name attribute
console.log(data.get("email"));
console.log(data.has("terms")); // unchecked checkboxes are omitted
const values = Object.fromEntries(data); // { name, email, phone, password, terms }
});
Remember: every value from a form is a string (or a File). Convert numbers with Number() and trim text before validating.
The Constraint Validation API
Each input has a validity object telling you which rule failed, plus methods to check and customise validation:
| Property / method | Meaning |
|---|---|
input.checkValidity() | true if all rules pass |
input.validity.valueMissing | required but empty |
validity.typeMismatch | not a valid email/URL |
validity.tooShort / tooLong | length rules |
validity.patternMismatch | doesn't match pattern |
validity.customError | you set one with setCustomValidity |
input.setCustomValidity(msg) | mark invalid with a message ("" clears it) |
A complete, accessible validator
const form = document.querySelector("#signup");
const messages = {
name: { valueMissing: "Enter your name", tooShort: "Name must be at least 2 characters" },
email: { valueMissing: "Enter your email", typeMismatch: "Enter an email like name@example.com" },
phone: { patternMismatch: "Enter a 10-digit mobile number starting with 6–9" },
password: { valueMissing: "Create a password", tooShort: "Use at least 8 characters" },
};
function validateField(input) {
// custom rule on top of the built-in ones
if (input.name === "password") {
input.setCustomValidity(/\d/.test(input.value) ? "" : "Include at least one number");
}
const errorEl = document.querySelector(`#${input.id}-error`);
if (!errorEl) return input.checkValidity();
let message = "";
if (!input.validity.valid) {
const failed = Object.keys(messages[input.name] ?? {}).find((rule) => input.validity[rule]);
message = failed ? messages[input.name][failed] : input.validationMessage;
}
errorEl.textContent = message;
input.setAttribute("aria-invalid", message ? "true" : "false");
input.setAttribute("aria-describedby", errorEl.id);
return !message;
}
// validate a field when the user leaves it, then live while they fix it
form.addEventListener("focusout", (e) => {
if (e.target.matches("input")) validateField(e.target);
});
form.addEventListener("input", (e) => {
if (e.target.getAttribute("aria-invalid") === "true") validateField(e.target);
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
const inputs = [...form.querySelectorAll("input")];
const results = inputs.map(validateField);
if (results.includes(false)) {
inputs[results.indexOf(false)].focus(); // take the user to the first problem
return;
}
await submitSignup(form);
});
Good validation timing
- While typing the first timestay quiet – don't shout at half-typed input
- On leaving the field (blur)validate and show a message if wrong
- While fixing an invalid fieldre-validate on every input so the error clears instantly
- On submitvalidate everything and focus the first invalid field
Accessibility checklist
- Every input has a
<label>– placeholders are not labels. - Errors are text near the field, linked with
aria-describedby, announced witharia-live, and flagged witharia-invalid. - Don't rely on red colour alone; say what's wrong and how to fix it.
- Use the right
type,inputmodeandautocompleteso mobile keyboards and password managers help.
Submitting with fetch
async function submitSignup(form) {
const button = form.querySelector('[type="submit"]');
button.disabled = true; // prevent double submission
button.textContent = "Creating account…";
try {
const res = await fetch("/api/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(Object.fromEntries(new FormData(form))),
});
const body = await res.json();
if (!res.ok) {
// show server-side errors (e.g. "email already registered") on the right field
for (const [field, msg] of Object.entries(body.errors ?? {})) {
document.querySelector(`#${field}-error`).textContent = msg;
}
return;
}
location.assign("/welcome");
} catch {
showToast("Network problem – please try again.");
} finally {
button.disabled = false;
button.textContent = "Create account";
}
}
Client-side validation is for user experience, not security
Anyone can bypass browser JavaScript and send any request directly to your server. Always validate again on the server, and protect forms that change data with CSRF tokens.
Practice
Try it yourself
Add a "Confirm password" field and show "Passwords don't match" using
setCustomValidity.Show solution
const pw = document.querySelector("#password"); const confirmPw = document.querySelector("#confirm"); function checkMatch() { confirmPw.setCustomValidity(confirmPw.value === pw.value ? "" : "Passwords don't match"); } pw.addEventListener("input", checkMatch); confirmPw.addEventListener("input", checkMatch);
Quick check
What does new FormData(form) include?
All named, enabled fields – unchecked checkboxes and radios are left out.
How do you add a custom validation rule?
input.setCustomValidity("message") when invalid, and "" when valid.
Is front-end validation enough?
No – it improves the experience, but the server must validate everything again.
Summary
- Use HTML attributes for basic rules and FormData to read values (all strings).
- validity, checkValidity and setCustomValidity give precise, custom messages.
- Show accessible errors at the right time, prevent double submits, and always validate on the server too.
Interview practice: JavaScript DOM, events and browser API interview questions.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.