Tutorials JavaScript Forms & Validation
Ch 45 / 78
Chapter 45 Intermediate 8 min read JavaScript

Forms & Validation

Forms are the primary way users send data to your app. JavaScript gives you fine-grained control over form events, input values, and the Constraint Validation API — letting you validate fields in real time, display friendly error messages, and prevent bad data from ever reaching the server.

Advertisement
What you'll learn
Accessing form elements and reading input values in JavaScript
Handling submit, input, change, and focus events
Using the HTML5 Constraint Validation API
Custom error messages with setCustomValidity()
Real-time validation with visual feedback on every keystroke
Building a complete registration form with full validation

Why Client-Side Validation Matters

Without validation, users can submit empty fields, malformed emails, weak passwords, or mismatched data — causing server errors and poor UX. There are two main approaches: rely on HTML attributes alone, or use JavaScript to take full control with real-time feedback, custom rules, and accessible error messages.

Without JS Validation
Rely only on HTML attributes or skip validation entirely.
  • Browser default popups — ugly and unstylable
  • No real-time feedback while the user types
  • Errors only shown after submit — frustrating UX
  • Cannot enforce complex rules (password strength, etc.)
  • No cross-field validation (e.g. password confirm)
With JS Validation
Full control over when, how, and what errors are shown.
  • Custom, styled error messages inline with each field
  • Real-time feedback on input / blur
  • Complex rules — regex, length, strength, matching
  • Accessible ARIA attributes and screen reader support
  • Submit only when the entire form is valid

Accessing Forms & Input Values

JavaScript gives you several ways to access a form and its controls. The cleanest approach uses document.querySelector or the named document.forms collection. Each input's value is exposed via .value (text), .checked (checkboxes/radios), or .files (file inputs).

Form DOM structure — one form, many inputs
<form id="regForm"> submit listener
<input name="email">
<input name="password">
<button type="submit">
Submit event bubbles from button → form — one listener handles all
JavaScript — Accessing Forms
// ── 3 ways to get a form ──────────────────────────────────
const form1 = document.querySelector("#regForm"); // by id ✅
const form2 = document.forms["regForm"]; // named collection
const form3 = document.forms[0]; // index (avoid)

// ── Reading input values ──────────────────────────────────
const email = form1.elements["email"].value; // text
const agree = form1.elements["agree"].checked; // checkbox
const gender = form1.elements["gender"].value; // radio group
const file = form1.elements["avatar"].files[0]; // file input

// ── FormData — grab ALL fields at once ────────────────────
const data = new FormData(form1);
console.log(data.get("email")); // "user@example.com"
console.log([...data.entries()]); // all key-value pairs

Form Events

JavaScript fires several events during the form lifecycle. Understanding when each fires — and on which element — determines how and where you attach listeners.

Event Fires on When Common use
submit <form> User clicks submit or presses Enter Final validation, prevent default & send data
input <input> Every keystroke / value change Real-time feedback, character counter
change <input>, <select> After blur — value actually changed Validate after user finishes typing
focus <input> Field receives focus (does not bubble) Show hints, highlight active field
blur <input> Field loses focus (does not bubble) Validate a single field when user leaves it
focusin / focusout <input> Same as focus/blur but does bubble Delegation-friendly focus handling
reset <form> User clicks a reset button Clear custom error states
Form submit flow — step by step
1
User clicks Submit (or presses Enter)
The browser fires the submit event on the <form> element.
2
Call e.preventDefault()
Stops the default page reload / form POST so JavaScript can handle submission.
3
Run validation logic
Check each field — required, pattern, min/max length, cross-field rules (passwords match).
4a
Invalid — show errors & stop
Display inline error messages, add error classes, focus the first invalid field.
4b
Valid — submit the data
Send via fetch() / axios, or call form.submit() programmatically.
JavaScript — Form Events
const form = document.querySelector("#regForm");
const email = document.querySelector("#email");

// ── submit ─────────────────────────────────────────────────
form.addEventListener("submit", (e) => {
e.preventDefault(); // stop page reload
if (validateForm()) sendData();
});

// ── input — real-time feedback ─────────────────────────────
email.addEventListener("input", () => {
validateEmail(email.value); // check on every keystroke
});

// ── blur — validate when user leaves the field ────────────
email.addEventListener("blur", () => {
if (!email.value) showError(email, "Email is required");
});

// ── focus — clear errors when re-entering the field ───────
email.addEventListener("focus", () => clearError(email));

// ── reset — clear all custom validation states ────────────
form.addEventListener("reset", () => {
form.querySelectorAll(".field-error").forEach(el => el.textContent = "");
form.querySelectorAll(".invalid").forEach(el => el.classList.remove("invalid"));
});

The Constraint Validation API

The browser exposes a built-in Constraint Validation API on every form element. It lets you check validity programmatically, read which specific rule failed, and set custom error messages — all without reinventing the wheel. Key methods are checkValidity(), reportValidity(), and setCustomValidity().

validity.valueMissing
required field is empty
validity.typeMismatch
Value doesn't match the input type (e.g. email)
validity.patternMismatch
Value doesn't match the pattern attribute regex
validity.tooShort
Value is shorter than minlength
validity.tooLong
Value is longer than maxlength
validity.rangeUnderflow
Number is below min
validity.rangeOverflow
Number is above max
validity.customError
A custom message was set via setCustomValidity()
validity.valid
true when ALL constraints pass
JavaScript — Constraint Validation API
const email = document.querySelector("#email");

// ── checkValidity() — returns true/false ──────────────────
if (!email.checkValidity()) {
const v = email.validity;
if (v.valueMissing) showError(email, "Email is required.");
else if (v.typeMismatch) showError(email, "Enter a valid email.");
}

// ── reportValidity() — checks AND shows browser bubble ────
form.addEventListener("submit", (e) => {
e.preventDefault();
if (!form.reportValidity()) return; // shows native error tooltips
sendData();
});

// ── setCustomValidity() — custom rule (password confirm) ──
function validateConfirm() {
const pw = document.querySelector("#password").value;
const confirm = document.querySelector("#confirm");

if (confirm.value !== pw) {
confirm.setCustomValidity("Passwords do not match.");
} else {
confirm.setCustomValidity(""); // ← empty string = valid again!
}
}
document.querySelector("#confirm").addEventListener("input", validateConfirm);

Real-Time Validation Pattern

The best user experience validates on input (while typing) but only starts showing errors after the first blur (so you don't scold a user mid-typing). A reusable validate() helper and showError() / clearError() utilities make this clean.

JavaScript — Reusable Validation Helpers
// ── Helpers ───────────────────────────────────────────────
function showError(input, message) {
const field = input.closest(".form-field");
field.classList.add("invalid");
field.classList.remove("valid");
field.querySelector(".field-error").textContent = message;
input.setAttribute("aria-invalid", "true");
}

function clearError(input) {
const field = input.closest(".form-field");
field.classList.remove("invalid");
field.classList.add("valid");
field.querySelector(".field-error").textContent = "";
input.removeAttribute("aria-invalid");
}

// ── Per-field validator ────────────────────────────────────
function validateField(input) {
const v = input.validity;
if (v.valid) { clearError(input); return true; }

if (v.valueMissing) showError(input, `${input.labels[0].textContent} is required.`);
else if (v.typeMismatch) showError(input, `Enter a valid ${input.type}.`);
else if (v.tooShort) showError(input, `Minimum ${input.minLength} characters.`);
else if (v.patternMismatch) showError(input, input.dataset.patternMsg || "Invalid format.");
else if (v.customError) showError(input, input.validationMessage);
return false;
}

// ── Attach — validate on blur, re-check on input after touched
document.querySelectorAll(".form-field input").forEach(input => {
input.addEventListener("blur", () => { input.dataset.touched = "1"; validateField(input); });
input.addEventListener("input", () => { if (input.dataset.touched) validateField(input); });
});

// ── Form submit — run all validators ──────────────────────
form.addEventListener("submit", (e) => {
e.preventDefault();
const inputs = [...form.querySelectorAll("input, textarea, select")];
const allValid = inputs.map(validateField).every(Boolean);
if (allValid) sendData(); else inputs.find(i => !i.validity.valid)?.focus();
});
Advertisement

Password Strength Validation

Password fields need custom rules that HTML5 attributes can't express alone. Use a regex test or a scoring function and call setCustomValidity("") to clear the error once the password is strong enough.

JavaScript — Password Strength & Confirm
const pwInput = document.querySelector("#password");
const cfmInput = document.querySelector("#confirm");
const strengthBar = document.querySelector("#strengthBar");

// Strength rules
const rules = [
{ regex: /.{8,}/, label: "8+ chars" },
{ regex: /[A-Z]/, label: "Uppercase" },
{ regex: /[a-z]/, label: "Lowercase" },
{ regex: /[0-9]/, label: "Number" },
{ regex: /[^A-Za-z0-9]/, label: "Special char" },
];

function getScore(pw) {
return rules.filter(r => r.regex.test(pw)).length; // 0–5
}

pwInput.addEventListener("input", () => {
const score = getScore(pwInput.value);
const labels = ["Too weak", "Weak", "Fair", "Good", "Strong", "Very Strong"];
strengthBar.dataset.score = score;
strengthBar.textContent = labels[score];

if (score < 3) {
pwInput.setCustomValidity("Password is too weak. Add uppercase, numbers, or symbols.");
} else {
pwInput.setCustomValidity(""); // clears the custom error
}

if (cfmInput.value) validateConfirm(); // re-check confirm if already typed
});

function validateConfirm() {
cfmInput.setCustomValidity(
cfmInput.value !== pwInput.value ? "Passwords do not match." : ""
);
validateField(cfmInput);
}
cfmInput.addEventListener("input", validateConfirm);

Complete Registration Form Example

Putting it all together — a registration form with name, email, password, password confirm, and terms checkbox, all validated on blur and on submit.

HTML — Form Structure
<!-- Each field wrapped in .form-field so helpers can find error span -->
<form id="regForm" novalidate>

<div class="form-field">
<label for="name">Full Name</label>
<input id="name" name="name" type="text" required minlength="2">
<span class="field-error" aria-live="polite"></span>
</div>

<div class="form-field">
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<span class="field-error" aria-live="polite"></span>
</div>

<div class="form-field">
<label for="password">Password</label>
<input id="password" name="password" type="password" required minlength="8">
<div id="strengthBar"></div>
<span class="field-error" aria-live="polite"></span>
</div>

<div class="form-field">
<label for="confirm">Confirm Password</label>
<input id="confirm" name="confirm" type="password" required>
<span class="field-error" aria-live="polite"></span>
</div>

<div class="form-field">
<label><input type="checkbox" id="terms" required> I agree to the Terms</label>
<span class="field-error"></span>
</div>

<button type="submit">Create Account</button>
</form>
JavaScript — Full Validation Script
const form = document.querySelector("#regForm");
const pwInput = document.querySelector("#password");
const cfInput = document.querySelector("#confirm");

// ── Helpers ───────────────────────────────────────────────
const showError = (input, msg) => {
const wrap = input.closest(".form-field");
wrap.classList.add("invalid"); wrap.classList.remove("valid");
wrap.querySelector(".field-error").textContent = msg;
input.setAttribute("aria-invalid", "true");
};
const clearError = input => {
const wrap = input.closest(".form-field");
wrap.classList.remove("invalid"); wrap.classList.add("valid");
wrap.querySelector(".field-error").textContent = "";
input.removeAttribute("aria-invalid");
};

function validateField(input) {
const v = input.validity;
if (v.valid) { clearError(input); return true; }
if (v.valueMissing) showError(input, "This field is required.");
else if (v.typeMismatch) showError(input, "Invalid format.");
else if (v.tooShort) showError(input, `Min ${input.minLength} characters.`);
else if (v.customError) showError(input, input.validationMessage);
return false;
}

// ── Password confirm ──────────────────────────────────────
const checkConfirm = () =>
cfInput.setCustomValidity(cfInput.value !== pwInput.value ? "Passwords do not match." : "");
pwInput.addEventListener("input", checkConfirm);
cfInput.addEventListener("input", checkConfirm);

// ── Blur-then-live pattern ────────────────────────────────
form.querySelectorAll("input").forEach(input => {
input.addEventListener("blur", () => { input._touched = true; validateField(input); });
input.addEventListener("input", () => { if (input._touched) validateField(input); });
});

// ── Submit ────────────────────────────────────────────────
form.addEventListener("submit", e => {
e.preventDefault();
checkConfirm();
const fields = [...form.querySelectorAll("input")];
const isValid = fields.map(validateField).every(Boolean);
if (!isValid) { fields.find(f => !f.validity.valid)?.focus(); return; }

console.log("✅ Form valid — sending data", Object.fromEntries(new FormData(form)));
// await fetch('/api/register', { method:'POST', body: new FormData(form) })
});

// ── Reset ─────────────────────────────────────────────────
form.addEventListener("reset", () => {
form.querySelectorAll("input").forEach(i => {
i._touched = false; i.setCustomValidity(""); clearError(i);
});
});

Quick Reference — Key Methods & Properties

Method / Property Returns Description
input.value string Current text value of the input
input.checked boolean Whether a checkbox / radio is checked
input.validity ValidityState Object with flags for each constraint (see above)
input.checkValidity() boolean Returns true if all constraints pass; does NOT show UI
input.reportValidity() boolean Same as checkValidity but also shows native browser tooltip
input.setCustomValidity(msg) void Set a custom error; empty string "" clears the error
input.validationMessage string The message that would appear in a browser tooltip
new FormData(form) FormData Collects all named inputs at once; use with fetch()
form.elements["name"] HTMLElement Access any control by its name attribute
form.reset() void Clears all inputs to their default values

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel