The pattern Attribute
You'll learn how to use regular expressions with the pattern attribute to create custom validation rules for text inputs.
What is the pattern Attribute?
The pattern attribute lets you define custom validation rules using regular expressions (regex). While HTML input types like email or url provide built-in validation, pattern gives you precise control over what text formats you'll accept.
Think of it like creating a template with specific rules: "only letters and numbers," "must start with a capital letter," or "exactly 6 digits." The browser automatically checks user input against your pattern and prevents submission if it doesn't match.
How to Use pattern
Add the pattern attribute to text-based inputs (text, tel, email, url, password, search) with a regular expression value:
<!-- Only allow lowercase letters -->
<input type="text" pattern="[a-z]+" required>
<!-- Exactly 5 digits (like a ZIP code) -->
<input type="text" pattern="\d{5}" required>
<!-- Username: 3-16 alphanumeric characters -->
<input type="text" pattern="[A-Za-z0-9]{3,16}" required>
Adding User-Friendly Messages
The default error message isn't always clear. Use the title attribute to explain what format you expect:
<input
type="text"
pattern="[A-Z]{2}\d{4}"
title="Format: Two uppercase letters followed by four digits (e.g., AB1234)"
required>
The browser will display your title text when validation fails, helping users understand what's wrong.
Important Notes
- The pattern must match the entire value (it's implicitly anchored with
^and$) - Only validates when the field has a value—combine with
requiredif needed - Works alongside other validation attributes
Key Takeaway: The pattern attribute uses regular expressions to define custom validation rules for text inputs, giving you precise control over acceptable input formats with built-in browser validation.