Forms and Constraint Validation

HTML's built-in form validation attributes, and how to read validity state or add an accessible custom error message alongside it.

                <input required type="email"> / input.validity.valid
              

Purpose

HTML form elements support built-in validation — required, type="email", minlength, pattern, and others — that the browser enforces automatically, including a default error UI. JavaScript can read that validation state and layer a custom, accessible message alongside it.

Syntax

<label for="email">Email</label> <input id="email" type="email" required />
const emailInput = document.querySelector('#email');

emailInput.addEventListener('invalid', (event) => {
  event.preventDefault(); // suppress the browser's default validation bubble
  showCustomError(emailInput, 'Please enter a valid email address.');
});

console.log(emailInput.validity.valid); // false if the current value fails validation
console.log(emailInput.validity.valueMissing); // true specifically if required and empty

Behavior notes

  • element.validity is a ValidityState object with several specific boolean flags (valueMissing, typeMismatch, tooShort, and others) — useful for showing a message specific to why validation failed, not just that it did.
  • The browser’s default validation UI is functional but not very customizable in appearance. Many apps suppress it (event.preventDefault() on invalid) and render their own message — which must still be programmatically associated with the input (via aria-describedby) and ideally announced, to remain accessible.
  • Client-side validation is a usability feature, not a security boundary — a form’s data must still be validated again wherever it’s actually processed (a server, for example), since client-side checks can always be bypassed.

Common mistakes

  • Relying on client-side validation as the only validation, which any direct request to the backend bypasses entirely.
  • Suppressing the browser’s default validation UI without replacing it with an equally accessible custom message — leaving no clear feedback at all for a sighted or assistive-technology user.

Runtime notes

Part of the HTML and DOM standards — browser-only.

Taught in these lessons

Related reference

Updated 2026-09-03