Sometimes you need users to type data in a very specific format — a phone number, a postal code, or a serial number. The pattern attribute on inputs lets you define a regular expression that the value must match. It is like having a tiny validation robot right in your HTML.
Basic Pattern Syntax
The pattern attribute takes a regular expression. The browser checks the input value against it on form submission. If it does not match, the browser shows a validation error. You can use the title attribute to give the user a hint about the expected format.
<input type="text" pattern="[A-Za-z]+" title="Letters only">
<input type="text" pattern="[0-9]{4}" title="Four digit code">
Common Real-World Patterns
Here are some patterns you will use again and again. Phone numbers, email-like patterns, and postal codes are probably the most common ones in everyday web forms.
<!-- US phone number: 123-456-7890 -->
<input type="tel" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" name="phone" title="123-456-7890">
<!-- US zip code: 12345 or 12345-6789 -->
<input type="text" pattern="[0-9]{5}(-[0-9]{4})?" name="zip" title="12345 or 12345-6789">
<!-- Credit card number: 16 digits -->
<input type="text" pattern="[0-9]{16}" name="card" title="16 digit card number">
Useful Pattern Building Blocks
Understanding a few common regex building blocks makes writing patterns much easier. The ^ and $ anchors ensure the whole value matches. \w matches letters and digits, . matches almost anything, and curly braces control repetition.
<!-- Only letters and numbers, 5-15 characters -->
<input type="text" pattern="\w{5,15}" title="5 to 15 letters or digits">
<!-- Must contain at least one letter and one number -->
<input type="text" pattern="(?=.*[a-zA-Z])(?=.*\d).+" title="Letters and numbers required">
<!-- No spaces allowed -->
<input type="text" pattern="\S+" title="No spaces please">
Combining Pattern with Other Attributes
Pattern works beautifully alongside required, minlength, and maxlength. This way you get multiple layers of validation — the field must not be empty, must be the right length, and must match the pattern.
<input type="text" name="username" required minlength="3" maxlength="15"
pattern="[a-zA-Z0-9_]+" title="3-15 characters, letters digits and underscores only">