Pattern and Title for Validation
What you'll learn: How to create custom validation rules for your form inputs using patterns and helpful error messages.
The Core Idea
Sometimes the built-in validations like required or type="email" aren't enough. You might need a phone number in a specific format, a product code with exact characters, or a username that follows special rules. The pattern attribute lets you define custom validation rules using regular expressions (regex), and the title attribute provides a friendly error message when someone enters invalid data.
Think of it like a bouncer at a club with a specific dress code. The pattern is the dress code rules, and the title is the polite explanation the bouncer gives you if you don't meet them.
How It Works
The pattern attribute accepts a regex pattern that the input value must match:
<input
type="text"
name="zipcode"
pattern="[0-9]{5}"
title="Please enter a 5-digit ZIP code"
required>
In this example, [0-9]{5} means "exactly 5 digits." If someone types "abc" or "123", the browser shows the validation error—and your title message explains what's expected.
Another example for a product code:
<input
type="text"
name="product"
pattern="[A-Z]{3}-[0-9]{4}"
title="Format: Three uppercase letters, dash, four numbers (e.g., ABC-1234)">
The browser won't let the form submit until the pattern matches, and hovering over or seeing the error displays your helpful title text.
Key Takeaway: Use pattern to enforce custom input formats with regex, and always include a title attribute to explain the expected format to your users in plain language.