Lesson 8 of 55 · HTML
Form Validation – Built‑in Constraints
Duration: 9 min
Browser‑Based Validation
HTML5 introduces constraint validation that runs automatically when a form is submitted.
<input type='email' name='email' required pattern='.+@example\.com' />
Common constraints
required– Field must not be empty.pattern– Regular expression match. Use thetitleattribute to explain the required format to users.min,max,step– Numeric range control.type='number',type='url',type='date'– Built‑in format checks.maxlength– Maximum number of characters.
Custom validation with JavaScript
const email = document.querySelector('input[name="email"]');
email.addEventListener('input', () => {
if (!email.checkValidity()) {
email.setCustomValidity('Please enter a corporate email ending with @example.com');
} else {
email.setCustomValidity('');
}
});
setCustomValidity overrides the default message. When the string is empty, the control is considered valid.
Validation UI
- Browsers display a native tooltip on invalid fields. You can style the
:invalidpseudo‑class to highlight errors. - For a fully custom UI, add
novalidateto the<form>and manage all checks in JavaScript. UsereportValidity()to trigger native messages if you need them.
Server‑side requirement
Never rely solely on client‑side validation; always re‑validate on the server to protect against tampering.
Quick checklist for validation
- All required fields have
required? ✅ - Custom patterns use
titlefor user guidance? ✅ setCustomValidityused where native messages insufficient? ✅- Server‑side validation planned for all inputs? ✅
novalidateonly used when you replace native checks? ✅
Tip: Use the Constraint Validation API (
checkValidity(),reportValidity()) for a smooth hybrid approach.