Sub topic 9
Built-in validation with attributes
This chapter assumes you can write a basic form with labeled controls and know how name and value produce submitted data. No JavaScript is needed here.
What the browser does for you
HTML attributes can declare rules for a control, such as "must be filled in", "at least 3 characters" or "a number from 1 to 10". When the user submits the form, the browser checks every rule. If any control fails, the browser cancels the submission, moves focus to the first invalid control, and shows a message next to it.
This is called constraint validation. It needs no script, it works with the keyboard, and screen readers announce the messages. The messages themselves are written by the browser. They differ between browsers and follow the user's language.
The core attributes
The table shows which attributes apply to which controls. An attribute on an unsupported type is silently ignored.
| Attribute | Rule | Applies to |
|---|---|---|
| `required` | A value must be present | Most inputs, `select`, `textarea` |
| `minlength`, `maxlength` | Length limits in characters | Text-like inputs, `textarea` |
| `min`, `max` | Numeric or date range | `number`, `range`, date and time types |
| `step` | Allowed increments | Same as `min` and `max` |
| `pattern` | Value must match a regular expression | `text`, `search`, `url`, `tel`, `email`, `password` |
| `type` | Value must have the right syntax | `email`, `url`, `number`, date types |
required
For text-like controls, required fails when the value is the empty string. A value of three spaces is not empty, so it passes. Trim the value on the server, or use pattern to forbid blank input.
required behaves differently on choice controls:
- A required checkbox must be checked. This is the usual way to enforce "I accept the terms".
- A required radio button makes the whole group (all radios with the same
name) require a selection. Putrequiredon at least one radio, and by convention on all of them. - A required
selectfails when the selected option has an emptyvalue. That is how a placeholder option works.
<label for="topic">Topic</label>
<select id="topic" name="topic" required>
<option value="">Choose one…</option>
<option value="billing">Billing</option>
<option value="technical">Technical</option>
</select>minlength and maxlength
minlength and maxlength count characters, specifically UTF-16 code units. Some emoji count as two. Two behaviors surprise people:
- An empty field never fails
minlength. Addrequiredif empty is not allowed. minlengthis only checked after the user has edited the value. A value set by a script or by thevalueattribute is not flagged, thoughmaxlengthis still enforced when the user types.
maxlength also stops the user from typing past the limit, so a "too long" message rarely appears in practice.
min, max, and step
For type="number", min and max set the range. For date, month, week, time and datetime-local, they take values in that type's format, such as min="2026-01-01".
step defines which values are valid. The valid values are the min value (or the value attribute if there is no min) plus whole multiples of step. With min="0" step="5", the values 0, 5 and 10 are valid and 7 is not. The default step for number is 1, which rejects decimals such as 2.5. For prices, use step="0.01". To allow any decimal, use step="any".
type as a validator
Choosing type="email" or type="url" turns on syntax checking without any other attribute. The email check is deliberately loose. It accepts a@b, because that is technically a valid address, so it will not catch every typo. type="url" requires a scheme, so example.com fails and https://example.com passes. Add the multiple attribute to type="email" to accept a comma-separated list.
For type="number", if the user types text such as 12abc, the browser keeps an empty value and flags a bad input. The browser gives no hint in the submitted data, so a server only sees an empty field.
pattern
pattern takes a regular expression, written without slashes or flags. The browser matches the whole value as if the expression were wrapped in ^(?: and )$, so you do not add anchors.
<label for="zip">ZIP code</label>
<input id="zip" name="zip" type="text" inputmode="numeric"
required pattern="[0-9]{5}" title="Enter exactly five digits">Details that matter in practice:
- An empty value passes
pattern. Pair it withrequiredwhen needed. - The
titletext is appended to the browser's message. Do not rely on it alone, because touch devices and screen readers may not expose it. Put the format hint in visible text, ideally linked witharia-describedby. - An invalid regular expression is ignored by the browser with no warning, so check the console while developing.
- Inside a character class, escape a hyphen or place it last. Modern browsers compile patterns in a stricter mode (the
vflag), where an unescaped hyphen or some punctuation inside a class can make the whole pattern invalid and therefore ignored.
A complete example
This form combines several rules. Save it as an .html file and open it. Try submitting with each field wrong.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Book a table</title>
</head>
<body>
<form action="/book" method="post">
<p>
<label for="name">Name</label>
<input id="name" name="name" type="text" required minlength="2" maxlength="60">
</p>
<p>
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
</p>
<p>
<label for="guests">Guests (1 to 8)</label>
<input id="guests" name="guests" type="number" min="1" max="8" step="1" value="2" required>
</p>
<p>
<label for="date">Date</label>
<input id="date" name="date" type="date" min="2026-12-01" required>
</p>
<p>
<label for="code">Voucher (optional, two letters and four digits)</label>
<input id="code" name="code" type="text" pattern="[A-Z]{2}[0-9]{4}" title="For example AB1234">
</p>
<p>
<label><input type="checkbox" name="terms" value="yes" required> I accept the booking terms</label>
</p>
<button type="submit">Book</button>
</form>
</body>
</html>The voucher field has no required, so leaving it empty is fine. If the user types something, it must match the pattern.
Controls that are skipped
Validation does not apply to every control. The browser skips controls that are:
disabledreadonlytype="hidden"- inside a
datalist - buttons of type
resetorbutton
A readonly field with required and an empty value will not block submission. If you need the value checked, do not use readonly.
Turning validation off
Add novalidate to the <form> to skip all checks on submit. A submit button with formnovalidate skips checks only when that button is used. This is the standard way to build a "Save draft" button next to a strict "Publish" button:
<button type="submit">Publish</button>
<button type="submit" formnovalidate>Save draft</button>Scripts also matter here. Calling form.requestSubmit() runs validation like a button click. Calling form.submit() skips validation and fires no submit event.
Common mistakes
- Treating validation as security. Anyone can remove attributes in developer tools or send a request directly. Always validate again on the server. The attributes are a convenience for honest users.
- Using
patternon the wrong type. Ontype="number"it is ignored. Usemin,maxandstepinstead. - Forgetting
requiredwithminlengthorpattern. Empty values pass both. - Over-strict patterns. Rejecting names with apostrophes or accents, or phone numbers with spaces, turns away real users. Validate the shape you truly need.
- Relying on the default messages. They cannot explain your business rules. Styling and custom messages are covered in later chapters.
Exercises
Exercise
A text field has pattern="[0-9]{5}" but no required. The user leaves it empty and clicks submit. Does the form submit, and why?
Show answer
Yes, it submits. An empty value is not checked against pattern, so no constraint fails. To force input, add required to the field.
Exercise
An input has type="number" min="0" max="100" step="5". Which of these values are valid: 0, 45, 47, 100, 105?
Show answer
0, 45 and 100 are valid. 47 fails step (it is not a multiple of 5 from the minimum 0). 105 fails max.
Exercise
Your form has a "Save draft" button that should work even when required fields are empty. Which attribute do you add, and where?
Show answer
Add formnovalidate to the draft button, which is a <button type="submit">. The other submit button still triggers validation.