What is the pattern attribute?

pattern specifies a regular expression that the value of a text-like input (text, tel, email, url, password, search) must fully match for the form to be valid. It is anchored automatically, so pattern="[0-9]{6}" means exactly six digits. Pair it with a clear hint and a title or custom message, because the default error is generic.

Rules

  • The whole value must match: browsers wrap it as ^(?:pattern)$.
  • Since 2023, browsers compile it with the v flag (Unicode sets), so some characters must be escaped inside character classes, such as - at certain positions, or the pattern is ignored. Test patterns in the browser.
  • Empty values are not checked by pattern; add required if the field must be filled.
  • No flags allowed (case-insensitive matching is not available; include both cases).

Examples

  • Indian PIN code: [1-9][0-9]{5}.
  • Username: [a-z0-9_]{3,16}.
  • Hex color: #[0-9a-fA-F]{6}.
  • Strong password hint: (?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{12,}.

Messages

  • title text is shown in some browsers as part of the error tooltip.
  • Better: helper text visible near the field, and setCustomValidity() for a specific message in the invalid event.
  • Style with :user-invalid.

When not to use it

  • For emails and URLs, prefer type="email" and type="url".
  • For numbers with ranges, type="number" with min/max, or inputmode="numeric" plus pattern for codes.
  • For complex rules (dates, cross-field checks), validate in JavaScript and on the server.

Code example

html
1<style>
2 body { font-family: system-ui; }
3 form { display: grid; gap: 6px; max-width: 320px; }
4 input:user-invalid { border: 2px solid #dc2626; }
5 small { color: #475569; }
6</style>
7<form id="f">
8 <label for="pin">PIN code</label>
9 <input id="pin" name="pin" inputmode="numeric" pattern="[1-9][0-9]{5}" required aria-describedby="pin-hint">
10 <small id="pin-hint">6 digits, cannot start with 0</small>
11
12 <label for="user">Username</label>
13 <input id="user" name="user" pattern="[a-z0-9_]{3,16}" required aria-describedby="user-hint">
14 <small id="user-hint">3-16 characters: lowercase letters, numbers, underscore</small>
15
16 <label for="color">Brand color</label>
17 <input id="color" name="color" pattern="#[0-9a-fA-F]{6}" placeholder="#4f46e5">
18
19 <button>Save</button>
20</form>
21<script>
22 const user = document.getElementById("user");
23 user.addEventListener("invalid", () => {
24 user.setCustomValidity(user.validity.patternMismatch ? "Use only a-z, 0-9 and _, 3 to 16 characters." : "");
25 });
26 user.addEventListener("input", () => user.setCustomValidity(""));
27</script>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app