Native validation without JavaScript
HTML5 form validation lets the browser enforce rules declaratively through
attributes, exposing the result via the Constraint Validation API. This reference
covers every validation attribute, the ValidityState flag it sets, and the API
methods — plus a live tester for the pattern attribute.
How it works
Validation attributes constrain a control; on submit (or via a script call) the
browser checks each constraint and sets the matching ValidityState flag:
<input type="text" required minlength="3" maxlength="20"
pattern="[a-z0-9_]+" title="lowercase, digits, underscore">
const input = form.elements.username;
if (!input.checkValidity()) {
console.log(input.validity); // { patternMismatch: true, ... }
}
input.setCustomValidity(taken ? "Username is taken" : "");
form.reportValidity(); // shows the bubble on the first invalid field
The pattern regex is implicitly anchored to the whole value (^(?:...)$), so it
must match the entire string, not a substring.
Tips and notes
patternonly validates non-empty values — combine withrequiredto forbid blanks.- Always set a
titlealongsidepattern; browsers show it in the error bubble. min/max/stepapply to numeric and date types;stepmismatches setstepMismatch(e.g.step="5"rejects7).novalidateon the form orformnovalidateon a submit button skips all checks.- Style states with the
:valid,:invalid,:requiredand:user-invalidCSS pseudo-classes.