Native HTML Form Validation
By the end of this lesson you will be able to find out exactly why the browser thinks a field is wrong, show errors at the right moment, and replace the browser's message with your own, all with very little JavaScript.
Form Validation Basics introduced the attributes required, pattern, min, max and friends. This lesson looks under the hood. The full JavaScript API comes much later in Constraint Validation API; here we stay practical.
How the browser checks a form
Think of the TTE (travelling ticket examiner) on a train. He checks each ticket against a few rules: right date, right train, right coach. If one rule fails, he stops at that passenger.
The browser does the same when a form is submitted. It walks through every field and checks it against the rules you wrote as attributes. These rules are called constraints. If a field breaks one, the browser stops the submission, moves focus to the first bad field and shows a small popup message, often called the validation bubble.
Some fields are never checked. The standard calls them barred from constraint validation: disabled fields, readonly fields, type="hidden" fields and buttons. So required readonly does nothing useful.
The validity object
Every field has a validity property: an object of true/false flags, one per kind of problem, like a report card with a tick or cross per subject.
| Flag | True when |
|---|---|
valueMissing | A required field is empty |
typeMismatch | An email or url field does not look like one |
patternMismatch | The value does not match pattern |
tooShort / tooLong | The user typed fewer than minlength or more than maxlength characters |
rangeUnderflow / rangeOverflow | The value is below min or above max |
stepMismatch | The value is not one of the steps allowed by step |
badInput | The browser cannot understand what was typed, such as letters in a number field |
customError | Your script set a message with setCustomValidity() |
valid | None of the problems above |
The field's validationMessage property holds the text the browser would show in its bubble.
Step 1: run this inspector. Step 2: type in each field and watch the flags change. Try "abc" in the coupon box, 9 in the tickets box, and just the letter e in the tickets box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Validity inspector</title>
<style>
label { display: block; margin-top: 10px; }
pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
</style>
</head>
<body>
<label for="coupon">Coupon (5 to 8 capital letters or digits)</label>
<input id="coupon" required minlength="5" maxlength="8" pattern="[A-Z0-9]+">
<label for="tickets">Tickets (1 to 6)</label>
<input id="tickets" type="number" min="1" max="6" required>
<label for="mail">Email (optional)</label>
<input id="mail" type="email">
<pre id="out"></pre>
<script>
const flags = ["valueMissing", "typeMismatch", "patternMismatch", "tooShort", "tooLong",
"rangeUnderflow", "rangeOverflow", "stepMismatch", "badInput", "customError"];
function show() {
const lines = [];
for (const input of document.querySelectorAll("input")) {
const broken = flags.filter((f) => input.validity[f]);
lines.push(`${input.id}: valid=${input.validity.valid} flags: ${broken.join(", ") || "none"}`);
if (input.validationMessage) lines.push(` message: ${input.validationMessage}`);
}
document.querySelector("#out").textContent = lines.join("\n");
}
document.addEventListener("input", show);
show();
</script>
</body>
</html>Notice three things. The empty optional email is valid, because only required cares about empty fields. "abc" fails the pattern but tooShort stays false until you have typed in the box. And in most browsers a lone e in the number field gives badInput: the browser keeps the text on screen but treats the value as empty.
The validation bubble
The bubble appears when the user submits, or when your script calls reportValidity(). It has strict limits:
- It shows only the first invalid field, not all of them.
- Its text comes from the browser, in the browser's language, so a visitor with a Hindi browser may see a Hindi message on your English page.
- You cannot style it or choose where it appears, and in some browsers it vanishes after a few seconds.
That is fine for a short form. On a long admission form, users need to see every problem at once, so you write your own messages.
:invalid, :user-invalid and :user-valid
CSS can react to the same validity state:
| Selector | Matches |
|---|---|
:invalid / :valid | Right now, even before the user has touched the field |
:user-invalid | Only after the user has changed the field and moved on, or tried to submit |
:user-valid | The same timing, for fields that pass |
:invalid paints every empty required field red on page load, like being scolded before you start. :user-invalid waits. It has worked in Chrome, Firefox and Safari since 2023.
Combine it with :has() to style the whole field group, label included:
.field:has(input:user-invalid) label { color: crimson; }
.field:has(input:user-invalid) .hint { display: block; }Custom messages with setCustomValidity
Some rules cannot be written as attributes, such as "both mobile numbers must match". For those, call setCustomValidity("message") on the field. Any non-empty message makes the field invalid, sets customError and becomes its validationMessage. To make the field valid again, you must call setCustomValidity("") with an empty string.
That last rule causes the most common bug in this topic. If you set a message once and never clear it, the form can never be submitted, even after the user fixes the value. So run your check on every input event and always set something: the message or the empty string.
Two methods ask for a check:
checkValidity()returnstrueorfalsequietly.reportValidity()returns the same answer and shows the bubble for the first problem.
Your own messages with novalidate
Adding novalidate to the <form> stops the automatic check on submit. Nothing else changes: the constraints, the validity flags and checkValidity() all still work. You simply take charge of showing the messages.
Step 1: add novalidate and an empty error paragraph under each field. Step 2: on submit, read each field's validity and write a friendly message. Step 3: add the custom "numbers match" rule. Step 4: focus the first bad field. Run it and press the button with the form empty.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test drive booking</title>
<style>
label { display: block; margin-top: 12px; }
.err { color: crimson; margin: 4px 0; }
.err:empty { display: none; }
input:user-invalid { border: 2px solid crimson; }
</style>
</head>
<body>
<h1>Book a scooter test drive, Jaipur</h1>
<form id="booking" novalidate>
<label for="fullname">Full name</label>
<input id="fullname" required minlength="3" aria-describedby="fullname-err">
<p class="err" id="fullname-err"></p>
<label for="mobile">Mobile number</label>
<input id="mobile" type="tel" required pattern="[6-9][0-9]{9}" aria-describedby="mobile-err">
<p class="err" id="mobile-err"></p>
<label for="mobile2">Re-enter mobile number</label>
<input id="mobile2" type="tel" required aria-describedby="mobile2-err">
<p class="err" id="mobile2-err"></p>
<button>Book test drive</button>
</form>
<p id="done" role="status"></p>
<script>
const form = document.querySelector("#booking");
const mobile = document.querySelector("#mobile");
const mobile2 = document.querySelector("#mobile2");
function checkMatch() {
mobile2.setCustomValidity(mobile2.value === mobile.value ? "" : "The two numbers do not match.");
}
mobile.addEventListener("input", checkMatch);
mobile2.addEventListener("input", checkMatch);
function messageFor(input) {
const v = input.validity;
if (v.valueMissing) return "Please fill in this field.";
if (v.tooShort) return `Please use at least ${input.minLength} characters.`;
if (v.patternMismatch) return "Enter 10 digits starting with 6, 7, 8 or 9.";
return input.validationMessage; // any other problem: use the browser's text ("" if valid)
}
form.addEventListener("submit", (event) => {
event.preventDefault(); // demo only: nothing is sent
checkMatch();
let firstBad = null;
for (const input of form.querySelectorAll("input")) {
const message = messageFor(input);
document.querySelector(`#${input.id}-err`).textContent = message;
if (message && !firstBad) firstBad = input;
}
if (firstBad) {
firstBad.focus();
} else {
document.querySelector("#done").textContent = "Booked. We will call you to fix a time.";
}
});
</script>
</body>
</html>All three messages appear together, each under its own field, and aria-describedby links each message to its input so screen readers read it on focus. Type two different numbers and submit: the custom message appears. Make them match and it clears, because checkMatch() sets an empty string. Error design for screen readers goes further in Accessible Form Error Handling.
Common mistakes
- Never clearing
setCustomValidity. The field stays invalid forever. Always set""when the value is fine. novalidatewith no replacement messages. The form now submits anything. If you switch the bubble off, show your own errors.- Styling with
:invalid. Empty forms look broken on load. Use:user-invalid. requiredon areadonlyfield. Read-only fields are skipped by validation.
Interview questions
1. What is the difference between :invalid and :user-invalid?
:invalid matches as soon as a field breaks a constraint, even on page load. :user-invalid matches only after the user has interacted with the field or tried to submit the form. That makes it the better choice for error styles.
2. Why might a form refuse to submit even after the user fixed every field?
Usually a script called setCustomValidity() with a message and never cleared it. Any non-empty custom message keeps the field invalid. The fix is to call setCustomValidity("") when the value is acceptable.
3. What is the difference between checkValidity() and reportValidity()?
Both return true if the field or form is valid. checkValidity() is silent, while reportValidity() also shows the browser's message for the first problem. Both fire an invalid event on each invalid field.
4. Does novalidate remove the constraints from a form?
No. It only stops the browser checking automatically on submit. The validity flags, checkValidity() and the :invalid selector still work, so you can build your own messages on top of them.
Key points
- Every field has a
validityobject with flags such asvalueMissing,patternMismatchandbadInput. - The validation bubble shows only the first problem, in the browser's language, and cannot be styled.
- Use
:user-invalidand:user-validso errors appear only after interaction. setCustomValidity("message")adds your own rule;setCustomValidity("")clears it.checkValidity()checks quietly;reportValidity()also shows the bubble.novalidateturns off the automatic check, not the constraints; then you must show your own messages.
Exercise
Build a "Register for the Kochi coding club" form with novalidate. It needs a required email, a required age from 14 to 25, and a password with at least 8 characters plus a "confirm password" field. Show all errors at once under each field when the user submits, with friendly messages for valueMissing, typeMismatch, rangeUnderflow, rangeOverflow and tooShort. Use setCustomValidity() for the password match, and focus the first bad field.
Show solution
<form id="club" novalidate>
<label for="email">Email</label>
<input id="email" type="email" required aria-describedby="email-err">
<p class="err" id="email-err"></p>
<label for="age">Age</label>
<input id="age" type="number" min="14" max="25" required aria-describedby="age-err">
<p class="err" id="age-err"></p>
<label for="pw">Password</label>
<input id="pw" type="password" minlength="8" required aria-describedby="pw-err">
<p class="err" id="pw-err"></p>
<label for="pw2">Confirm password</label>
<input id="pw2" type="password" required aria-describedby="pw2-err">
<p class="err" id="pw2-err"></p>
<button>Register</button>
</form>
<script>
const form = document.querySelector("#club");
const pw = form.querySelector("#pw"), pw2 = form.querySelector("#pw2");
const match = () => pw2.setCustomValidity(pw.value === pw2.value ? "" : "Passwords do not match.");
pw.addEventListener("input", match);
pw2.addEventListener("input", match);
function messageFor(i) {
const v = i.validity;
if (v.valueMissing) return "This field is required.";
if (v.typeMismatch) return "Enter an email like name@example.com.";
if (v.rangeUnderflow) return `You must be at least ${i.min}.`;
if (v.rangeOverflow) return `The club is for ages up to ${i.max}.`;
if (v.tooShort) return `Use at least ${i.minLength} characters.`;
return i.validationMessage; // custom or other errors, "" when valid
}
form.addEventListener("submit", (e) => {
match();
if (form.checkValidity()) return; // all good: let the form submit
e.preventDefault();
let first = null;
for (const i of form.querySelectorAll("input")) {
const m = messageFor(i);
document.querySelector(`#${i.id}-err`).textContent = m;
if (m && !first) first = i;
}
first.focus();
});
</script>checkValidity() still works under novalidate, so the script lets a valid form through and only builds messages when something is wrong.
Quick Quiz
1. A field has required and readonly, and it is empty. What happens on submit?
Readonly fields are barred from constraint validation, so required has no effect on them.
2. Which flag is true when a user types letters the browser cannot read into a number field?
badInput means the browser could not convert what the user typed into a value.
3. What must you call to remove a custom error?
Only an empty string clears the custom message and makes the field valid again.
4. What does novalidate change?
The constraints and validity flags remain; only the automatic check and bubble on submit are skipped.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
