In this section, we will learn what the pattern attribute is and how to use it.
What is pattern Attribute in HTML <input> Tag?
Those input elements that take text content from users like textbox or password box etc., sometimes we want to make sure the data that users enter into the field follows a pattern!
For example, we might want only characters (with no number in it) for a specific field.
Or we might want users to enter a text that starts with specific character, etc.
This is where we could use the pattern attribute.
The pattern attribute takes one value and that’s a regular expression value! The value users enter to the target field then will be compared against the regular expression value of the pattern attribute to see if they match or not. If the user’s value didn’t match the pattern, the browsers will automatically show an error to mention that the user did not entere a correct data.
The <input> types that can use the pattern attribute are:
Text, date, search, url, tel, email, and password.
HTML pattern Attribute in <input> Tag Syntax:
<input type = “type” pattern = “regular-expression-value”>
<input> Tag pattern Attribute Values
The value we set for the pattern attribute is a regular expression.
Example: using pattern attribute in HTML <input> tag
See the Pen using pattern attribute in HTML <input> tag by Omid Dehghan (@odehghan) on CodePen.
For this particular example, the value of the area code field according to the value set for the pattern attribute should only be 3 digital numbers.
So if we set more or less than 3 digital numbers or put a non-digital value in the field, browsers will automatically show an error saying the inserted value does not match the pattern and so no form data will be submitted to a server.