The pattern attribute validates a text-like field's value against a regular expression — for format rules more specific than any built-in input type checks on its own.
Syntax
<input type="text" pattern="regex-here" title="A hint shown when it fails">
Basic Example
<label for="pincode">PIN Code</label>
<input type="text" id="pincode" name="pincode" pattern="[0-9]{6}" title="Enter a 6-digit PIN code">
Browser output: submission is blocked with a native message if the value doesn't consist of exactly 6 digits — the title attribute's text is shown as part of that native validation message in most browsers.
How It Works
The browser checks the field's entire value against the regular expression in pattern — the match must cover the whole value, not just part of it (the browser automatically anchors the pattern, so you don't need to add ^/$ yourself).
Important Attributes
| Attribute | Purpose |
|---|---|
pattern | A JavaScript-flavored regular expression the value must fully match |
title | Human-readable explanation shown as part of the native error message — genuinely important for usability here |
Real-World Example
<label for="coupon">Coupon Code</label>
<input type="text" id="coupon" name="coupon" pattern="[A-Z]{4}[0-9]{2}" title="4 uppercase letters followed by 2 digits, e.g. SAVE20">
A specific format requirement (4 letters, 2 digits) that no built-in input type could check on its own — exactly the kind of custom rule pattern exists for.
Comparison: required vs pattern
required | pattern | |
|---|---|---|
| Checks | Whether a value was entered at all | Whether an entered value matches a specific shape |
| Can be used together? | Yes — very commonly combined on the same field | |
Common Mistakes
- Writing an overly strict or genuinely incorrect regex that rejects valid input the field should actually accept
- Omitting
title, leaving users with no clue what format is actually expected when validation fails
Best Practices
- Always pair
patternwith a cleartitleexplaining the expected format - Test the regex thoroughly against real, valid example values before shipping it
Accessibility Considerations
The title text is what makes a pattern mismatch actually understandable — without it, users (including screen reader users) only get a generic "please match the requested format" message with no real guidance.
SEO Considerations
No direct ranking effect.
Browser & Modern HTML Notes
pattern only applies to type="text", tel, email, url, search, and password — it has no effect on number, date, or other non-text-like input types.
Mini Practice
- Build a coupon code field with a
patternand a cleartitleexplaining the format. - Combine
requiredandpatternon the same field.