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

Try it yourself
Result

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 it yourself
Result

Try "hello" in the email field: type="email" and type="url" check the basic format automatically.

Ranges and lengths

Try it yourself
Result
AttributeApplies toChecks
requiredMost controlsNot empty
min, maxnumber, range, date, timeWithin range
stepnumber, range, date, timeAllowed increments
minlength, maxlengthText inputs, textareaNumber of characters
patternText inputsMatches a regular expression
typeemail, urlFormat

pattern

Try it yourself
Result

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

Try it yourself
Result

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

Important: anyone can edit your HTML in developer tools, turn off JavaScript, or send data straight to your server. Browser validation exists to help honest users fix mistakes quickly. The server must always validate every value again before using it.

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".

Try it yourself

Try it yourself
Result