HTML Form Validation
Validation means checking that the data in a form makes sense before it is used: a required field is not empty, an email looks like an email, an age is a sensible number. Modern browsers can do most of this for you, with nothing but HTML attributes. When you need more, a small JavaScript API lets you add custom rules and messages.
Built-in validation attributes
| Attribute / type | Rule it enforces |
|---|---|
required |
Field must not be empty (checkbox must be ticked) |
type="email" / type="url" |
Value must look like an email address / URL |
minlength / maxlength |
Length of text |
min / max |
Lowest / highest number, date or time |
step |
Value must be a multiple of the step (from min) |
pattern |
Value must match a regular expression |
When the user submits, the browser checks every field. If one fails, submission is cancelled, the first invalid field gets focus, and a message bubble explains the problem.
<style>
label { display: block; margin: 8px 0; font-family: sans-serif; }
</style>
<form id="signup">
<label>Name * <input name="name" required minlength="2"></label>
<label>Email * <input type="email" name="email" required></label>
<label>Age (13–120) <input type="number" name="age" min="13" max="120"></label>
<label>Zip code (5 digits) <input name="zip" pattern="\d{5}" title="Exactly five digits"></label>
<label><input type="checkbox" name="terms" required> I accept the terms *</label>
<button>Create account</button>
</form>
<p id="ok"></p>
<script>
// The submit event only fires after all built-in checks pass.
document.getElementById('signup').addEventListener('submit', (e) => {
e.preventDefault();
document.getElementById('ok').textContent = '🎉 Everything is valid!';
});
</script>Styling valid and invalid fields
CSS has pseudo-classes that react to validation state:
| Selector | Matches |
|---|---|
:valid / :invalid |
Fields that currently pass / fail their rules |
:required / :optional |
Fields with / without required |
:in-range / :out-of-range |
Numbers or dates inside / outside min–max |
:user-invalid |
Invalid fields the user has already interacted with |
:placeholder-shown |
Fields still showing their placeholder |
Plain :invalid paints a required field red before the user has typed anything, which feels unfriendly. :user-invalid (supported in current browsers) waits until the user has edited the field or tried to submit.
<style>
input { padding: 6px; border: 2px solid #bbb; border-radius: 6px; outline: none; }
input:valid { border-color: #2e9d4a; }
input:user-invalid { border-color: #d33; background: #fff3f3; }
.hint { color: #d33; font-size: 13px; visibility: hidden; }
input:user-invalid + .hint { visibility: visible; }
</style>
<form action="#">
<p><input type="email" required placeholder="email"> <span class="hint">Enter a valid email</span></p>
<p><input type="number" min="1" max="10" required placeholder="1–10"> <span class="hint">Pick 1 to 10</span></p>
</form>Custom rules with JavaScript
Some rules can't be expressed with attributes, such as "the two passwords must match". The Constraint Validation API lets you add them:
| Member | What it does |
|---|---|
input.setCustomValidity(msg) |
Marks the field invalid with your message; '' makes it valid again |
input.validity |
Object with flags like valueMissing, typeMismatch, tooShort, patternMismatch |
input.validationMessage |
The browser's (or your) error text |
form.checkValidity() |
Returns true/false without showing messages |
form.reportValidity() |
Checks and shows the message bubbles |
<form id="pw">
<p><label>Password <input type="password" id="p1" required minlength="8"></label></p>
<p><label>Repeat <input type="password" id="p2" required></label></p>
<button>Save</button>
</form>
<p id="status"></p>
<script>
const p1 = document.getElementById('p1');
const p2 = document.getElementById('p2');
function checkMatch() {
p2.setCustomValidity(p1.value === p2.value ? '' : 'Passwords do not match');
}
p1.addEventListener('input', checkMatch);
p2.addEventListener('input', checkMatch);
document.getElementById('pw').addEventListener('submit', (e) => {
e.preventDefault();
document.getElementById('status').textContent = '✅ Password saved (not really — this is a demo).';
});
</script>Your own error messages
If you prefer messages written inside the page instead of browser bubbles, add novalidate to the form and use the validity flags yourself:
<style>
.err { color: #c00; font-size: 14px; min-height: 1.2em; margin: 2px 0 10px; }
</style>
<form id="f" novalidate>
<label>Email <input type="email" id="email" required></label>
<div class="err" id="emailErr"></div>
<button>Subscribe</button>
</form>
<script>
const email = document.getElementById('email');
const err = document.getElementById('emailErr');
function explain() {
const v = email.validity;
if (v.valueMissing) return 'Please enter your email.';
if (v.typeMismatch) return 'That does not look like an email address.';
return '';
}
document.getElementById('f').addEventListener('submit', (e) => {
e.preventDefault();
err.textContent = explain();
if (!err.textContent) err.textContent = '✅ Subscribed!';
});
</script>Note: Client-side validation is a convenience for users, not a security measure. Anyone can switch it off or send data directly to your server, so always validate again on the server.
Tip: Good messages say how to fix the problem ("Use at least 8 characters") rather than only that something is wrong ("Invalid input").
Test yourself
When does the submit event fire on a form without novalidate?
- Always, even if fields are invalid
- Only after all built-in validation passes
- Only when JavaScript calls it
- Before validation runs
How do you mark a field invalid with your own message in JavaScript?
input.invalid = trueinput.setCustomValidity('message')input.error('message')form.reject(input)
Why must the server validate data even if the HTML form already does?
- Browsers validate too slowly
- Client-side checks can be bypassed
- HTML validation only works offline
- It doesn't need to