Sub topic 3
Built-in constraint attributes
This chapter assumes you can write a basic HTML form with labels and inputs, and that you know how a form submission sends named values to a server. You do not need JavaScript here. Everything below works with markup alone.
What constraint attributes do
A constraint attribute is an HTML attribute that declares a rule a control's value must satisfy. When the user submits the form, the browser checks every rule. If any control fails, the browser cancels the submission, focuses the first failing control, and shows a message.
You declare the rules and the browser enforces them. The seven attributes covered here are required, minlength, maxlength, min, max, step, and pattern.
Each attribute applies only to certain controls. Putting an attribute on a control that doesn't support it does nothing, and no error is raised.
| Attribute | Rule | Applies to |
|---|---|---|
| `required` | A value must be present | Most inputs, `select`, `textarea` |
| `minlength` | At least N characters | Text-like inputs, `textarea` |
| `maxlength` | At most N characters | Text-like inputs, `textarea` |
| `min` | Value is at least N | Number, range, and date/time inputs |
| `max` | Value is at most N | Number, range, and date/time inputs |
| `step` | Value fits a regular interval | Number, range, and date/time inputs |
| `pattern` | Value matches a regular expression | Text-like inputs |
"Text-like inputs" means text, search, url, tel, email, and password.
A worked example
This is the signup form used throughout the tutorial. Each control carries one or more constraints.
<form id="signup" action="/signup" method="post">
<label for="email">Email</label>
<input id="email" name="email" type="email" required autocomplete="email">
<label for="username">Username</label>
<input id="username" name="username" required minlength="3" maxlength="20"
pattern="[a-z0-9_]+" title="Lowercase letters, digits, and underscores only">
<label for="age">Age</label>
<input id="age" name="age" type="number" min="18" max="120" step="1">
<button type="submit">Sign up</button>
</form>Here is what the browser enforces on submit:
- The email field must not be empty, and its text must look like an email address. The
type="email"check is covered in the next chapter. - The username must be present, 3 to 20 characters long, and made only of lowercase letters, digits, and underscores.
- The age, if filled in, must be a whole number from 18 to 120.
Age has no required, so leaving it empty is valid. Keep that in mind, because it is the most common surprise in this chapter.
Empty values skip most rules
Only required rejects an empty value. Every other constraint is skipped when the field is empty. An empty username passes minlength="3", an empty age passes min="18", and an empty field passes pattern.
This is deliberate. It lets you separate "optional field" from "optional field, but valid if given". If a value is mandatory, add required as well as the other rules.
required
required makes an empty value invalid. How "empty" is judged depends on the control:
- Text-like inputs and
textarea: the value is the empty string. - Checkbox: the box must be checked. This suits "I accept the terms" fields.
- Radio buttons:
requiredon any one radio in a same-named group requires that one of them be selected. Put it on every radio in the group anyway, so the markup reads clearly. select: the selected option must have a non-empty value. For the check to work, the first option needs an emptyvalue, which acts as a placeholder.
<label for="country">Country</label>
<select id="country" name="country" required>
<option value="">Choose a country</option>
<option value="ca">Canada</option>
<option value="de">Germany</option>
</select>
<label>
<input type="checkbox" name="terms" value="yes" required>
I accept the terms
</label>If the first option were <option>Canada</option> with no value attribute, its value would be "Canada", and the select would always be valid.
minlength and maxlength
These count the characters in a text value. maxlength also changes behavior as the user types, because the browser stops accepting characters at the limit. The user rarely sees a "too long" error, since typing is blocked first. A value set by a script, or pasted in some browsers, can still exceed the limit and be flagged.
minlength has a quirk. Browsers apply the "too short" check only after the user has edited the value. A field pre-filled by the server with a short value, or filled by a script, is not flagged until the user changes it. Don't rely on minlength to catch bad stored data.
The length is measured in UTF-16 code units. Most characters count as one, but an emoji or other character outside the Basic Multilingual Plane counts as two. A maxlength="10" field may therefore accept fewer than ten visible emoji. Measure the length on the server using the same rule you present to users.
Neither attribute works on type="number". To limit a number, use min and max.
min, max, and step
These three attributes apply to numeric and date/time controls: number, range, date, month, week, time, and datetime-local.
minandmaxset an inclusive range. A value belowminfails with a "range underflow", and a value abovemaxfails with a "range overflow".stepsets the allowed interval. The default is 1 for numbers.
Step is measured from a starting point called the step base. The step base is the min value if there is one. Otherwise it is the value attribute, and failing that, zero. A value is valid when it equals the step base plus a whole multiple of the step.
<label for="qty">Quantity (odd numbers)</label>
<input id="qty" name="qty" type="number" min="1" max="9" step="2">
<label for="price">Price</label>
<input id="price" name="price" type="number" min="0" step="0.01">
<label for="angle">Angle</label>
<input id="angle" name="angle" type="number" step="any">In the first field, the valid values are 1, 3, 5, 7, and 9, because the step base is 1. The value 2 fails even though it is inside the range. The price field accepts amounts in cents. The step="any" keyword turns off the interval check, so any decimal is allowed.
The unit of step depends on the type:
| Type | Unit of `step` | Default step |
|---|---|---|
| `number`, `range` | The number itself | 1 |
| `date` | Days | 1 |
| `week` | Weeks | 1 |
| `month` | Months | 1 |
| `time` | Seconds | 60 |
| `datetime-local` | Seconds | 60 |
The time default of 60 means the picker offers whole minutes. To accept seconds, set step="1".
A common error is leaving the default step on a field that needs decimals. A type="number" field with no step rejects 19.99, because 19.99 is not a whole number of steps from the base. Add step="0.01" or step="any".
pattern
pattern takes a regular expression, written without delimiters or flags. The value must match the whole expression.
<input name="zip" inputmode="numeric" pattern="[0-9]{5}" title="Five digits">
<input name="sku" pattern="[A-Z]{3}-[0-9]{4}" title="Format ABC-1234" required>Points to know:
- The browser anchors the pattern for you.
[0-9]{5}behaves like^(?:[0-9]{5})$, so you should not add^and$. A value like123456fails. - Do not write
/.../. Slashes are treated as literal characters. - Browsers use JavaScript regular expression syntax, with the
vflag in current browsers anduin older ones. Some escapes that work in ordinary JavaScript patterns are errors in these modes. A hyphen inside a character class is the usual trap: write[\w-]as[\w\-]if the pattern stops working. - If the pattern is not a valid regular expression, the browser ignores it silently. A broken pattern means no validation, not an error. Check the pattern in the browser console with
new RegExp("^(?:" + pattern + ")$", "v"). - Use the
titleattribute to describe the format. Most browsers append it to the default message, so write it as a description of the expected format, not as an error sentence.
A pattern checks shape, not truth. [0-9]{5} accepts 00000, which is not a real ZIP code. Treat patterns as a quick filter.
Controls that are not validated
A control is exempt from constraint checking, whatever attributes it carries, in these cases:
- It is
disabled. Disabled controls are also left out of the submitted data. - It is
readonly. Read-only controls are submitted but never checked. - It is
type="hidden", or a button such astype="submit"ortype="reset". - It is inside a
datalistelement.
This leads to a gotcha. If you mark a field readonly and required, the user cannot fix an empty value, and the browser will not complain either. Use readonly only for values that are already correct.
How the browser decides
The diagram shows what happens for each control when the user submits.
If any control ends up invalid, the browser cancels the submit event's default action. The submit event does not fire at all, so a submit listener never sees an invalid form unless you turned validation off. Chapter on the browser's reporting UI covers that.
Seeing which rule failed
Each failed rule sets a flag on the control's validity object. You can inspect the flags from the console to debug a constraint. This preview of the Constraint Validation API is enough to check your attributes.
const field = document.getElementById('username');
const failed = [];
for (const key in field.validity) {
if (field.validity[key] === true && key !== 'valid') failed.push(key);
}
console.log(failed.length ? failed : 'valid');
console.log(field.validationMessage);The flags that match this chapter's attributes are:
| Attribute | Flag set on failure |
|---|---|
| `required` | `valueMissing` |
| `minlength` | `tooShort` |
| `maxlength` | `tooLong` |
| `min` | `rangeUnderflow` |
| `max` | `rangeOverflow` |
| `step` | `stepMismatch` |
| `pattern` | `patternMismatch` |
Common errors
- Expecting
minlengthorpatternto reject an empty field. Addrequired. - Adding
minlengthtotype="number". It has no effect. Useminandmax. - Wrapping the pattern in slashes or adding anchors. The browser already anchors it.
- Forgetting
stepfor decimal values. - Treating these attributes as security. They run in the user's browser, which the user controls. A client can remove the attributes or send a request directly. The server must repeat every rule.
Exercise
A field is declared as <input name="code" type="number" min="10" max="50" step="5">. Which of these values does the browser accept: 10, 12, 45, 55, and an empty field? Explain each.
Show answer
It accepts 10, 45, and the empty field. The step base is min, which is 10, so valid values are 10, 15, 20, and so on up to 50. 10 and 45 are on that grid and inside the range. 12 fails with stepMismatch because it is not 10 plus a multiple of 5. 55 fails with rangeOverflow because it is above 50. The empty field passes because the field has no required, and empty values skip every rule except required.
Exercise
You want a "nickname" field that is optional, but if the user fills it in, it must be 2 to 12 letters or digits. Write the input. Then say whether a value of two spaces would be accepted.
Show answer
<input name="nickname" minlength="2" maxlength="12" pattern="[A-Za-z0-9]+" title="Letters and digits only">. There is no required, so an empty value is valid. Two spaces would be rejected, because they are not empty, so the rules apply, and spaces do not match the pattern [A-Za-z0-9]+. Without the pattern, two spaces would pass minlength="2".