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.
submit, input, change, and
focus events
setCustomValidity()
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.
- 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)
- 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).
// ── 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 pairsForm 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 |
submit event on the
<form> element.
e.preventDefault()fetch() / axios, or call
form.submit() programmatically.
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().
required field is emptytype (e.g. email)
pattern attribute regex
minlengthmaxlengthminmaxsetCustomValidity()
true when ALL constraints passconst 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.
// ── 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();
});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.
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.
<!-- 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>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
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.