HTML Length and Pattern Constraints
Limit text length
minlength and maxlength count UTF-16 code units for applicable text controls. A short user-entered value can fail minlength. An empty optional field is not made required by minlength. Browsers normally prevent typing beyond maxlength.
<label> Nickname <input minlength="3" maxlength="8"></label>An empty value is valid. Type two characters to see tooShort.
Match the whole value
pattern uses a regular expression (a rule describing permitted text). [A-Z]{2}[0-9]{3} means exactly two ASCII uppercase letters followed by three ASCII digits. HTML matches the entire nonempty value; do not wrap the pattern in slash delimiters.
<label> Product code (AB123) <input pattern="[A-Z]{2}[0-9]{3}" value="AB12"></label>AB12 fails patternMismatch; AB123 passes.
Combine requirements and visible instructions
Combine required with a pattern when an empty value is unacceptable. Explain the format in visible text; title alone is insufficient. Length constraints are checked for user edits, not reliably by assigning a value in script.
<label for="pin">Access code</label><p id="hint">Enter exactly four ASCII digits.</p><input id="pin" required pattern="[0-9]{4}" aria-describedby="hint" inputmode="numeric">Empty is missing; 0123 is accepted as text, including its leading zero.
Common mistakes and practice
Use number constraints for quantities, not pattern on number inputs. A pattern is not a sanitizer. Modern HTML compiles pattern using Unicode-aware v-mode regular expressions; advanced escaping is outside this lesson. Test your pattern with valid, invalid and empty inputs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Length and Pattern Constraints — Knowledge Check
Apply the control concepts taught in this lesson.
Does minlength make an empty optional field invalid?
Which value matches [A-Z]{2}[0-9]{3}?
How is maxlength measured?
Where should format instructions appear?
What can assigning .value fail to reproduce?