HTML Form Validation Explained
Form validation is the checking that happens before a form’s data is accepted, Does the email look like an email? Is the required field filled in? Is the number within range? HTML form validation does a surprising amount of this with nothing but attributes, no JavaScript needed, and it gives visitors quick feedback before anything is sent to your server.
This guide explains the built-in tools, how to customize them with JavaScript, and why you still need to check everything again on the server.
How built-in validation works
When someone submits a form, the browser checks each field against the rules you set, if a field fails, the browser stops the submission, focuses the first problem field, and shows a message.
The form’s submit event does not fire at all while validation is failing, which is worth remembering when you write JavaScript, Fields that pass are left alone, and the form goes through once everything is valid.
<form action="/signup" method="post">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
<label for="username">Username</label>
<input type="text" id="username" name="username" required minlength="3" maxlength="20">
<button type="submit">Create account</button>
</form>
That form validates without a line of JavaScript.
Leave the email empty and the browser complains, type something that is not an email address and it complains again, enter a two-letter username and it points out the minimum length.
The validation attributes
| Attribute | Works on | What it checks | Best for |
|---|---|---|---|
| required | Most inputs, select, textarea | The field is not empty, or a box is checked | Mandatory fields and consent checkboxes |
| minlength and maxlength | Text-like inputs and textarea | Number of characters | Usernames, passwords, and short bios |
| min and max | Number, range, and date types | The value falls within a range | Quantities, ages, and booking dates |
| step | Number, range, and date types | The value matches an allowed increment | Whole numbers or prices in cents |
| pattern | Text, search, url, tel, email, password | The value matches a regular expression | Custom formats such as codes or usernames |
| type | Input | Built-in format, such as email or url | Free validation for common data |
Type-based checks
Some input types validate on their own. type="email" checks for a basic email shape, and type="url" expects a full address with a scheme, the check is deliberately loose, it accepts anything that looks roughly right, so an address like a@b passes, and it cannot tell you whether the mailbox exists only sending a confirmation email can do that.
The pattern attribute
The pattern attribute takes a regular expression, two details catch people out, the pattern is automatically anchored to the whole value, so you do not add ^ and $ yourself, and you write it without the surrounding slashes.
It also only works on text-based input types, so putting it on type="number" does nothing.
<input
type="text"
name="username"
pattern="[a-zA-Z0-9_]{3,20}"
title="3 to 20 letters, numbers, or underscores"
required>
The title attribute is often used to explain the pattern, and some browsers include it in the error message.
Do not rely on that alone, though, since support is inconsistent, put the instructions in visible text near the field.
Turning built-in validation off
Sometimes you want to handle validation entirely yourself, adding novalidate to the form element tells the browser to skip its checks on submit.
A button can also opt out by itself with formnovalidate, which is useful for a “Save draft” button that should work even when required fields are empty.
<form novalidate>
...
<button type="submit">Submit</button>
<button type="submit" formnovalidate>Save draft</button>
</form>
The Constraint Validation API
The browser exposes its validation system to JavaScript, which lets you read the results and write your own messages, every form field has a few useful members.
The checkValidity() method returns true or false.
The reportValidity() method does the same and also shows the browser’s message.
The validationMessage property holds the text the browser would show. And the validity object tells you exactly what went wrong, with flags such as valueMissing, typeMismatch, patternMismatch, tooShort, rangeUnderflow, and customError.
const email = document.querySelector("#email");
email.addEventListener("input", () => {
if (email.validity.valueMissing) {
email.setCustomValidity("Please enter your email address.");
} else if (email.validity.typeMismatch) {
email.setCustomValidity("That does not look like an email address.");
} else {
email.setCustomValidity("");
}
});
The setCustomValidity() method is the one to be careful with, passing it a message marks the field invalid and sets that message, passing an empty string clears the error.
If you forget to reset it, the field stays invalid forever, and the form will refuse to submit no matter what the person types.
Checking rules the attributes cannot express
Custom validation shines when a rule depends on more than one field.
A classic example is confirming a password:
const password = document.querySelector("#password");
const confirm = document.querySelector("#confirm");
function checkMatch() {
confirm.setCustomValidity(
confirm.value === password.value ? "" : "Passwords do not match."
);
}
password.addEventListener("input", checkMatch);
confirm.addEventListener("input", checkMatch);
Styling valid and invalid fields
CSS gives you the :valid and :invalid pseudo-classes, but they apply from the moment the page loads, so an empty required field is already marked invalid before anyone has touched it.
A page full of red borders on first load is a poor welcome, the :user-invalid and :user-valid pseudo-classes fix this by waiting until the person has interacted with the field, and current browsers support them.
input:user-invalid {
border-color: #c0392b;
outline-color: #c0392b;
}
input:user-valid {
border-color: #2e7d32;
}
Do not rely on color alone to show an error, some people cannot tell red from green, so pair the color with text or an icon.
Making error messages accessible
The browser’s default bubbles are accessible enough in many cases, but they cannot be styled, and they vanish quickly, if you show your own messages, connect them to their fields so assistive technology can announce them, link the message to the input with aria-describedby, and set aria-invalid="true" on the field when it has an error.
Place the message in an element that is announced when it changes, such as one with role="alert" or an aria-live region, keep the wording specific, telling people what to fix and not only that something is wrong. “Enter a date after today” helps far more than “Invalid input”.
<label for="age">Age</label>
<input type="number" id="age" name="age" min="18" max="120" aria-describedby="age-error">
<p id="age-error" role="alert"></p>
Always validate on the server too
Client-side validation is a convenience for honest visitors, it is not a security measure, because anyone can disable it, edit the HTML in developer tools, or send a request directly to your server without using the form at all.
Your server must check every value again, as if the browser had done nothing that includes length limits, formats, and anything that touches a database or a file system, treat browser validation as the friendly first layer and server validation as the real one.
For most forms, start with the attributes and the right input types, they cost almost nothing and work everywhere.
Add setCustomValidity when you want friendlier wording or a rule that spans fields, turn on novalidate and build your own system only when the design needs full control over how and when errors appear, and in that case lean on the Constraint Validation API so you are not reinventing the checks.
And whichever route you take, finish with server-side validation.
Common mistakes to avoid
The most common one is trusting the browser checks and skipping the server, close behind are forgetting to reset setCustomValidity(""), putting pattern on an input type that ignores it, and using :invalid styles that flash red on page load.
Others include relying on placeholders for instructions, writing vague error messages, and making required fields invisible to screen reader users by marking them only with a color.
One more subtle trap is that minlength only triggers after the user has edited the field, so a value filled in by your own script will not be flagged as too short.
Discover more from Developer Hint
Subscribe to get the latest posts sent to your email.
