Pattern Attribute in HTML: What It Is and How to Use It
pattern attribute in HTML is used on input fields to specify a regular expression that the input value must match for the form to be valid. It helps ensure users enter data in a specific format, like a phone number or email pattern, before submitting the form.How It Works
The pattern attribute works like a rulebook for what kind of text a user can type into an input box. Imagine you want someone to enter a phone number in a certain style, like 3 digits, a dash, then 4 digits. The pattern attribute lets you write a simple rule (called a regular expression) that checks if the typed text fits that style.
When the user tries to submit the form, the browser looks at the input and compares it to the pattern. If it doesn’t match, the form won’t submit and the browser shows a message asking the user to fix the input. This helps catch mistakes early, like typing letters where only numbers are allowed.
Think of it like a gatekeeper that only lets through answers that follow the rules you set, making your form data cleaner and easier to use.
Example
This example shows a form input for a US phone number that must be 3 digits, a dash, then 3 digits, another dash, and 4 digits (like 123-456-7890). The pattern attribute enforces this format.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Pattern Attribute Example</title> </head> <body> <form> <label for="phone">Phone Number (format: 123-456-7890):</label><br> <input type="text" id="phone" name="phone" pattern="\d{3}-\d{3}-\d{4}" required> <br><br> <button type="submit">Submit</button> </form> </body> </html>
When to Use
Use the pattern attribute when you want to make sure users enter data in a specific format without writing extra code. It is great for simple checks like phone numbers, postal codes, dates, or custom ID formats.
For example, if you run an online store and want customers to enter a zip code in the right format, the pattern attribute can help prevent mistakes. It works well for quick validation on the client side before sending data to the server.
However, for very complex validations or security checks, you should also validate data on the server side because users can bypass client-side rules.
Key Points
- The
patternattribute uses regular expressions to define allowed input formats. - It works only on input types like
text,search,tel,url,email, andpassword. - Browsers show a default error message if the input does not match the pattern when submitting.
- Always combine with the
requiredattribute if the field must not be empty. - Client-side validation with
patternimproves user experience but does not replace server-side validation.