Master Form Validation in Javascript: Learn How to Improve Your Forms Now!
Why Validate Forms?
Form validation ensures users submit correct and complete data before it's processed, improving both data quality and user experience.
Basic Validation Example
function validateForm() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
if (name.trim() === "") {
alert("Name is required");
return false;
}
if (!email.includes("@")) {
alert("Enter a valid email");
return false;
}
return true;
}
HTML5 Built-in Validation
<input type="email" required />
<input type="text" minlength="3" maxlength="20" required />
Best Practices
- Validate on both the client side (for instant feedback) and server side (for security).
- Show clear, specific error messages next to the relevant field.
- Use regular expressions for pattern-based checks like emails and phone numbers.
Validating on Submit Without Inline Handlers
Modern code attaches a listener to the form instead of using an onsubmit attribute, and shows errors next to fields rather than in pop-up alerts. Adding novalidate to the form turns off the browser's own bubbles so your custom messages take over, while the HTML5 rules still work through the Constraint Validation API.
<form id="signup" novalidate>
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<small class="error" id="email-error"></small>
<label for="phone">Mobile</label>
<input id="phone" name="phone" type="tel" required pattern="[6-9][0-9]{9}">
<small class="error" id="phone-error"></small>
<label for="pass">Password</label>
<input id="pass" name="pass" type="password" required minlength="8">
<label for="confirm">Confirm password</label>
<input id="confirm" name="confirm" type="password" required>
<small class="error" id="confirm-error"></small>
<button type="submit">Create account</button>
</form>
const form = document.getElementById("signup");
function showError(input) {
const box = document.getElementById(input.id + "-error");
if (!box) return;
box.textContent = input.validity.valid ? "" : input.validationMessage;
input.setAttribute("aria-invalid", String(!input.validity.valid));
}
form.addEventListener("submit", (event) => {
const pass = form.elements.pass;
const confirm = form.elements.confirm;
confirm.setCustomValidity(
confirm.value === pass.value ? "" : "Passwords do not match"
);
if (!form.checkValidity()) {
event.preventDefault();
[...form.elements].forEach(showError);
form.querySelector(":invalid").focus();
}
});
How the Constraint Validation API Works
Every input has a validity object with flags such as valueMissing, typeMismatch, patternMismatch, tooShort and rangeOverflow. The browser updates these flags from attributes like required, type, pattern and minlength. Three methods do most of the work:
checkValidity()returns true or false for one field or the whole form.setCustomValidity(message)marks a field invalid with your own rule; passing an empty string clears it.reportValidity()checks and also shows the browser's default message.
Checking flags lets you write friendlier messages, for example "Enter a 10-digit mobile number" when patternMismatch is true. The browser's default validationMessage text depends on the user's language settings, so replacing it with your own wording keeps messages consistent across devices. In the example above, the password check runs on submit because it compares two fields, something plain HTML attributes cannot express.
Feedback While the User Types
Validating every keystroke can feel aggressive, because errors appear before the user finishes typing. A balanced approach is to validate when a field loses focus, then switch to live checking once it has shown an error:
form.querySelectorAll("input").forEach((input) => {
input.addEventListener("blur", () => showError(input));
input.addEventListener("input", () => {
if (input.getAttribute("aria-invalid") === "true") showError(input);
});
});
Mistakes to Avoid
- Trusting the browser alone. Anyone can bypass client-side checks, so the server must repeat every rule before saving data.
- Overly strict email patterns. Complex regular expressions often reject real addresses; a simple format check plus a confirmation email works better.
- Clearing the form on error. Keep what the user typed so they only correct the faulty field.
- Colour-only error signals. Pair red borders with text, and link messages to fields using
aria-describedbyfor screen readers. - Forgetting to reset custom validity. If
setCustomValidityis never cleared, the field stays invalid forever. - Disabling the submit button with no explanation. Users cannot tell what is missing; show messages instead.
Ready to master real-world JavaScript development?
Learn JavaScript hands-on with mentor-led, live sessions.