Form validation
Form validation is checking that what a user typed into a form is complete and sensible before it is sent: a required field is filled, an email looks like an email, a password is long enough, two password fields match. In the browser, validation gives instant feedback so people can fix mistakes quickly. It combines built-in HTML attributes with JavaScript for rules HTML cannot express.
Let HTML do the simple checks
Modern browsers validate many rules on their own, with no script needed:
| Attribute | Rule it enforces |
|---|---|
required | The field cannot be empty. |
type="email", type="url" | The value must look like an email address or URL. |
minlength, maxlength | Text length limits. |
min, max, step | Number and date ranges. |
pattern | The whole value must match a regular expression. |
When the form is submitted, the browser blocks submission and shows a message beside the first invalid field. The CSS pseudo-classes :invalid and :valid, or the newer :user-invalid that waits until the user has interacted, let you style fields accordingly.
Adding custom rules with JavaScript
Some rules need code, such as "confirm password must match password". The Constraint Validation API lets you plug custom messages into the browser's own system, so they appear the same way as built-in ones.
<form id="signup" novalidate>
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<span class="error" id="email-error"></span>
<label for="pw">Password</label>
<input id="pw" name="pw" type="password" required minlength="8">
<label for="pw2">Confirm password</label>
<input id="pw2" name="pw2" type="password" required>
<span class="error" id="pw2-error"></span>
<button>Create account</button>
</form>
<script>
const form = document.getElementById('signup');
const pw = form.elements.pw;
const pw2 = form.elements.pw2;
function checkMatch() {
pw2.setCustomValidity(pw2.value === pw.value ? '' : 'Passwords do not match');
}
pw.addEventListener('input', checkMatch);
pw2.addEventListener('input', checkMatch);
form.addEventListener('submit', (event) => {
checkMatch();
if (!form.checkValidity()) {
event.preventDefault();
for (const field of form.elements) {
const box = document.getElementById(`${field.id}-error`);
if (box) box.textContent = field.validationMessage;
}
form.querySelector(':invalid')?.focus();
}
});
</script>
setCustomValidity('') with an empty string marks the field valid again. Any other text marks it invalid and becomes its validationMessage. The novalidate attribute turns off the browser's pop-up bubbles so the script can show messages in its own spans, while the rules themselves still apply.
When to show errors
Timing affects how friendly a form feels. Showing "invalid email" after the first letter is annoying. A common approach is to validate a field when it loses focus (the blur or change event), then re-check on every input once it has been marked wrong, so the message disappears as soon as the user fixes it. Always validate everything again on submit.
Making errors accessible
- Link each message to its input with
aria-describedbyso screen readers read it. - Set
aria-invalid="true"on fields with errors. - Do not rely on red colour alone; include text.
- Move focus to the first invalid field after a failed submit.
The mistake that matters most
Treating browser validation as security. Anyone can turn off JavaScript, edit the HTML in developer tools or send a request directly with a tool like curl, skipping your form entirely. Client-side checks are for user convenience. The server must validate every value again before saving it. A second, smaller mistake is writing over-strict patterns, such as an email regex that rejects valid addresses with a plus sign, or a phone pattern that refuses spaces. Keep rules as loose as the real requirement allows.
Summary of the approach
Start with HTML attributes for required fields, types, lengths and patterns. Add custom rules through setCustomValidity, show messages at sensible moments, make them accessible, and always validate again on the server.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.