Sub topic 3
Accessible Inline Error Messages
Assume you know basic HTML forms, CSS selectors, JavaScript event handlers, and HTTP form submission. Validation should help users correct input, but the server remains the source of truth.
Link each error to its control
An inline error is text placed near the field that needs correction. Give the error an id, then connect it with aria-describedby. Set aria-invalid="true" only when the field currently has an error.
<label for="username">Username</label>
<input id="username" name="username"
aria-describedby="username-error">
<p id="username-error" role="alert"></p>
<script>
const form = document.querySelector("form");
const username = document.querySelector("#username");
const error = document.querySelector("#username-error");
form.addEventListener("submit", (event) => {
error.textContent = "";
if (!username.validity.valid) {
event.preventDefault();
error.textContent = username.validationMessage;
username.setAttribute("aria-invalid", "true");
username.focus();
} else {
username.removeAttribute("aria-invalid");
}
});
</script>role="alert" asks assistive technology to announce newly inserted error text. Keep the message specific and explain how to fix the problem.
Cross-field validation
Some rules compare fields. For example, a confirmation password must match the original password. Use setCustomValidity(): an empty string means valid, while a non-empty string means invalid.
function checkMatch() {
confirmPassword.setCustomValidity(
password.value === confirmPassword.value
? ""
: "Passwords do not match."
);
}Run this function when either password changes. Clear the custom error when the values match.
Server-side validation
Client-side checks can be bypassed by disabling JavaScript or sending a direct HTTP request. The server must repeat every security and data-quality rule before saving or acting on submitted data.
| Layer | Main purpose |
|---|---|
| Browser | Fast, helpful feedback |
| Server | Trusted validation and authorization |
Return field-specific errors without echoing unsafe content. The client can display those errors beside the matching controls.
Async checks and testing
Availability checks, such as “is this username taken?”, require an asynchronous request. Debounce requests, handle failures, and prevent an old response from replacing newer input. Treat an unavailable check as an error or require submission to wait for a confirmed result.
Test empty, malformed, boundary, mismatched, and valid values. Also test keyboard focus, screen-reader announcements, JavaScript-disabled submission, server errors, and delayed or failed async responses.
Exercise
Why must the server repeat a client-side validation rule?
Show answer
A client can bypass browser validation and send an HTTP request directly, so only server-side validation can protect stored data and server actions.