Sub topic 2
How the Browser Reports Errors and When to Use `novalidate`
Assume you know HTML forms, CSS selectors, and basic JavaScript event handling. This chapter focuses on browser behavior and the Constraint Validation API.
Browser error reporting
When a user submits a form, the browser checks constraints such as required, type="email", minlength, and pattern. If a control is invalid, the browser usually prevents submission, focuses the first invalid control, and displays a browser-specific message.
flowchart TD
A[Submit form] --> B{Constraints valid?}
B -->|Yes| C[Submit data]
B -->|No| D[Show browser error]
D --> E[Focus first invalid control]
A --> F[form novalidate]
F --> G[Skip interactive browser validation]The novalidate attribute skips this automatic check for a form. It does not remove the constraints or prevent JavaScript from checking them.
Use novalidate when your JavaScript will provide a consistent error interface. Keep native validation when the browser messages and appearance are sufficient. A submit button can override the form setting with formnovalidate.
> callout note > novalidate is a user-interface choice, not a security feature. A client can modify the page or send an HTTP request directly.
Reading validity with the Constraint Validation API
The Constraint Validation API is the browser's JavaScript interface for form rules. checkValidity() returns a Boolean result. reportValidity() also asks the browser to display its normal error UI.
Each control has a validity object. Properties such as valueMissing, typeMismatch, and patternMismatch identify the failing rule.
<form id="profile">
<label>
Email
<input id="email" name="email" type="email" required>
</label>
<button type="submit">Save</button>
</form>
<script>
const form = document.querySelector("#profile");
form.addEventListener("submit", (event) => {
if (!form.checkValidity()) {
event.preventDefault();
form.reportValidity();
}
});
</script>Styling valid and invalid fields
Use :valid and :invalid to style validation states. These states can appear before interaction, so :user-valid and :user-invalid are often better for avoiding errors shown on page load.
input:user-invalid {
border: 2px solid #b00020;
}
input:user-valid {
border: 2px solid #087f23;
}Custom messages and rules
setCustomValidity() adds a custom constraint. A non-empty message makes the control invalid. An empty string clears that error.
const password = document.querySelector("#password");
const confirm = document.querySelector("#confirm");
function checkMatch() {
confirm.setCustomValidity(
password.value === confirm.value ? "" : "Passwords do not match."
);
}
password.addEventListener("input", checkMatch);
confirm.addEventListener("input", checkMatch);Exercise
Does novalidate stop checkValidity() from working?
Show answer
No. It skips the browser's automatic submit-time UI, but JavaScript can still call checkValidity() and reportValidity().