Module 11: Advanced HTML Forms and Validation
The Constraint Validation API
Understand validity states and how scripts can report errors without replacing browser validation unnecessarily.
The browser exposes validation information through the Constraint Validation API. Each form control has a validity object and methods such as checkValidity() and reportValidity().
<label for="username">Username</label>
<input id="username" name="username" required minlength="3">
<button type="button" id="check">Check field</button>
<p id="feedback" aria-live="polite"></p>
<script>
const username = document.querySelector("#username");
const feedback = document.querySelector("#feedback");
document.querySelector("#check").addEventListener("click", () => {
if (username.checkValidity()) {
feedback.textContent = "The field meets the browser's constraints.";
} else {
feedback.textContent = username.validationMessage;
username.reportValidity();
}
});
</script>
A custom validation message can be set with setCustomValidity(). Pass an empty string to clear it after the error is corrected. Forgetting to clear a custom message leaves the field invalid even when its value looks correct.
Native validation provides a useful baseline. Add custom messaging when it improves the experience, and make sure errors are visible and associated with the relevant controls. The server must repeat all important validation.