Key facts
How does the pattern attribute work?
The browser wraps the value of pattern as ^(?: + pattern + )$ and compiles it with the v flag, so the regex must match the whole value. While a non-empty value doesn't match, the field fails with patternMismatch and a normal submit is blocked.
| Fact | Detail |
|---|---|
| Anchoring | Implicit. pattern="\d{5}" means ^(?:\d{5})$, so 123456 fails. Adding your own ^ and $ is harmless but not needed. |
| Regex flag | The HTML Standard compiles it with the v flag, and current browsers follow it; older browsers used u. Under v, ( ) [ ] { } / - \ | must be escaped inside [ ], so write [\-.\s], not [-.\s]. |
| Works on | <input> with type text, search, url, tel, email or password. It does nothing on number, date or other types, or on <textarea>. |
| Empty field | Not checked: an empty value never fails pattern. Add required to make the field mandatory. |
| Invalid regex | Ignored: the field gets no pattern check at all. Browsers may log the error in the developer console. |
With multiple | On type="email" multiple, each address must match on its own. |
title | Describes the format. Browsers may show it with the error message or as a tooltip; Chrome and Firefox add it to their error message. |
| JavaScript | el.validity.patternMismatch is true while a non-empty value doesn't match. |
| Security | None. Anyone can POST without running it, so check the value on the server with the same regex. |
Sources: WHATWG HTML Standard: the pattern attribute · WHATWG: compiled pattern regular expression · WHATWG: suffering from a pattern mismatch · MDN: pattern · MDN: ValidityState.patternMismatch




