HTML pattern Attribute
Description
The HTML pattern attribute is used with form input fields (typically with <input> elements) to specify a regular expression that the input's value must match for the form to be submitted. This attribute is a powerful tool for client-side validation, allowing developers to restrict user input according to specific rules and formats without the need for JavaScript. It's especially useful for validating formats like email addresses, phone numbers, ZIP codes, and custom patterns.
The pattern attribute works with various types of input, such as text, date, search, url, tel, email, and password, enhancing the user experience by ensuring that the data entered matches the expected format before the form is sent to the server. When a user tries to submit a form with an input field that doesn't match the pattern, the browser will display a message prompting the user to adjust their input to the required format.
It's important to note that while the pattern attribute adds a layer of client-side validation, server-side validation is still necessary to ensure data integrity and security, as client-side validation can be bypassed.
Here's a simple example of the pattern attribute in action:
<form>
<label for="zip">Enter your ZIP code:</label>
<input type="text" id="zip" name="zip" pattern="d{5}" title="Five digit ZIP code" required>
<input type="submit">
</form>
In this example, the pattern attribute is set to d{5}, which means the input field will only accept a sequence of five digits, corresponding to a standard US ZIP code format. The title attribute is used to provide a message that will be displayed if the pattern validation fails, guiding the user on the expected input format.
Syntax
<input pattern="regexp">
Values
- regexpA regular expression. No forward slashes should be specified around the pattern text. No regular expression is applied if the attribute value is absent, an empty string, or invalid.
Applies To
Example
Browser Support
The following information will show you the current browser support for the HTML pattern attribute. Hover over a browser icon to see the version that first introduced support for this HTML attribute.
This attribute is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 26th March 2024
