How to Use Pattern Attribute for Validation in HTML Forms
Use the
pattern attribute inside an HTML input element to specify a regular expression that the input value must match for validation. This attribute works with the browser's built-in validation and prevents form submission if the pattern is not met.Syntax
The pattern attribute is added to an input element to define a regular expression that the input value must match.
pattern="regex": The regular expression the input must match.title="message": Optional. A message shown when the input does not match the pattern.required: Optional. Makes the input mandatory.
html
<input type="text" pattern="[A-Za-z]{3,}" title="Please enter at least 3 letters" required>
Example
This example shows a form with a text input that only accepts exactly 5 digits. If the input does not match, the browser shows a message and prevents submission.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Pattern Validation Example</title> </head> <body> <form> <label for="zip">Enter a 5-digit ZIP code:</label><br> <input type="text" id="zip" name="zip" pattern="\d{5}" title="Please enter exactly 5 digits" required> <br><br> <button type="submit">Submit</button> </form> </body> </html>
Output
A form with a label and a text box that only accepts exactly 5 digits; submitting with invalid input shows a browser error message.
Common Pitfalls
- Not escaping special characters properly in the pattern can cause it to fail.
- Using patterns that are too strict or too loose may confuse users.
- Relying only on pattern without
requiredallows empty input to pass validation. - Not providing a
titleattribute leaves users without helpful error messages.
html
<p>Wrong pattern (missing escape):</p> <input type="text" pattern="\d{5}" title="Enter 5 digits"> <p>Right pattern (escaped backslash):</p> <input type="text" pattern="\\d{5}" title="Enter 5 digits">
Quick Reference
| Attribute | Description |
|---|---|
| pattern | Regular expression the input must match |
| title | Message shown when pattern validation fails |
| required | Makes the input mandatory |
| type | Input type (e.g., text, email) affects validation behavior |
Key Takeaways
Use the pattern attribute with a regular expression to control input format.
Always include a title attribute to give users clear error messages.
Combine pattern with required to prevent empty inputs.
Test your regular expressions carefully and escape special characters.
Browser validation with pattern improves user experience without extra scripts.