Lesson 8 of 55
HTMLForm Validation – Built‑in Constraints
9 min
Course progress15%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 8 of 55
HTML9 min
Keep these ideas in mind as you work through the lesson.
HTML5 introduces constraint validation that runs automatically when a form is submitted.
<input type='email' name='email' required pattern='.+@example\.com' />
required – Field must not be empty.pattern – Regular expression match. Use the title attribute 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.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.
:invalid pseudo‑class to highlight errors.novalidate to the <form> and manage all checks in JavaScript. Use reportValidity() to trigger native messages if you need them.Never rely solely on client‑side validation; always re‑validate on the server to protect against tampering.
required? ✅title for user guidance? ✅setCustomValidity used where native messages insufficient? ✅novalidate only used when you replace native checks? ✅Tip: Use the Constraint Validation API (
checkValidity(),reportValidity()) for a smooth hybrid approach.