Form Validation
Browsers can check form input before it's sent — required fields, email formats, number ranges, lengths and custom patterns — and show messages without a single line of JavaScript. This lesson covers HTML's validation attributes and how to style valid and invalid fields.
required
Press Submit with the fields empty: the browser blocks submission, focuses the first problem and shows a message. required works on text inputs, checkboxes, radio groups, selects and textareas.
Type-based validation
Try "hello" in the email field: type="email" and type="url" check the basic format automatically.
Ranges and lengths
| Attribute | Applies to | Checks |
|---|---|---|
required | Most controls | Not empty |
min, max | number, range, date, time | Within range |
step | number, range, date, time | Allowed increments |
minlength, maxlength | Text inputs, textarea | Number of characters |
pattern | Text inputs | Matches a regular expression |
type | email, url | Format |
pattern
pattern takes a regular expression that must match the whole value. The title text is added to the error message, so describe the expected format in plain words.
Styling valid and invalid fields
CSS pseudo-classes reflect validity. :user-invalid and :user-valid only apply once the user has interacted with the field, so a fresh form isn't covered in red before anyone has typed — unlike the older :invalid, which matches immediately.
Turning built-in validation off
Add novalidate to the form to stop the browser blocking submission — for example, when JavaScript will show custom, inline error messages instead. The validation attributes still work as data for scripts through the Constraint Validation API (checkValidity(), validity, setCustomValidity()), covered in the JavaScript forms lesson.
Client-side validation isn't security
Good validation UX
- Tell people the rules up front ("8+ characters") instead of only after they fail.
- Be forgiving: accept spaces in card numbers, either case in codes, and so on — clean the data up on the server.
- Don't over-validate names and addresses; real-world names have apostrophes, hyphens, spaces and characters from every alphabet.
- Make error messages specific and polite: "Enter a date in 2026", not "Invalid input".