HTML Text pattern Property: Text Input Pattern Validation

June 19, 2025

HTML Text pattern Property: Validating User Input with Regular Expressions

The HTML pattern attribute, applicable to <input> elements with type “text,” “search,” “url,” “tel,” “email,” and “password,” provides a powerful way to enforce specific formats for user input. By defining a regular expression, you can ensure that the entered text conforms to a predefined structure, enhancing data integrity and user experience.

What is the pattern Property?

The pattern attribute specifies a regular expression that the input element’s value is checked against upon form submission. The form will only submit if the input value matches the defined pattern. This client-side validation helps prevent invalid data from being sent to the server.

Purpose of the pattern Property

The primary purpose of the pattern attribute is to:

  • Enforce specific input formats (e.g., phone numbers, zip codes, product codes).
  • Validate user input client-side, reducing server load and improving response time.
  • Provide immediate feedback to users, guiding them to enter data in the correct format.
  • Enhance data integrity by ensuring only valid data is submitted.

Syntax and Attributes

The pattern attribute takes a single value: a regular expression. This regular expression is used to validate the content of the input field.

<input type="text" id="myInput" name="myInput" pattern="[A-Za-z]{3}" title="Enter three letters" />

Here, pattern="[A-Za-z]{3}" enforces that the input must consist of exactly three alphabetic characters. The title attribute provides a user-friendly message explaining the expected format.

Attributes of the pattern Property

Attribute Value Description
`pattern` Regular Expression A regular expression that the input element’s value must match to be considered valid.
`title` (Optional) String Provides a descriptive message to the user about the expected format when the input doesn’t match the pattern. Browsers may display this as a tooltip on invalid input.

Note: The title attribute is highly recommended to provide clear instructions to the user on the expected input format. ℹ️

Examples of Using the pattern Property

Let’s explore some practical examples demonstrating the use of the pattern attribute. Each example includes the necessary HTML and explanations to illustrate different validation scenarios.

Basic Pattern Validation: 3-Letter Code

This example validates that the input field contains exactly three alphabetic characters.

<form>
  <label for="threeLetterCode">3-Letter Code:</label>
  <input
    type="text"
    id="threeLetterCode"
    name="threeLetterCode"
    pattern="[A-Za-z]{3}"
    title="Enter exactly three letters"
    required
  />
  <input type="submit" value="Submit" />
</form>

In this case, the input field requires the user to enter exactly three alphabetic characters (A-Z or a-z). The title attribute explains the expected format.

Validating a Phone Number

This example validates a US phone number format (e.g., 123-456-7890).

<form>
  <label for="phoneNumber">Phone Number:</label>
  <input
    type="tel"
    id="phoneNumber"
    name="phoneNumber"
    pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
    title="Enter phone number in format 123-456-7890"
    required
  />
  <input type="submit" value="Submit" />
</form>

Here, the pattern attribute ensures that the input matches the format XXX-XXX-XXXX, where X is a digit.

Validating a Zip Code

This example validates a US zip code format (5 digits or 5 digits followed by a hyphen and 4 digits).

<form>
  <label for="zipCode">Zip Code:</label>
  <input
    type="text"
    id="zipCode"
    name="zipCode"
    pattern="[0-9]{5}(-[0-9]{4})?"
    title="Enter a 5-digit zip code or 5+4 format (e.g., 12345 or 12345-6789)"
    required
  />
  <input type="submit" value="Submit" />
</form>

This pattern [0-9]{5}(-[0-9]{4})? allows for both 5-digit zip codes and the extended 5+4 format.

Validating a Custom Product Code

This example validates a product code that starts with two letters, followed by four digits.

<form>
  <label for="productCode">Product Code:</label>
  <input
    type="text"
    id="productCode"
    name="productCode"
    pattern="[A-Za-z]{2}[0-9]{4}"
    title="Enter a product code in the format LLNNNN (e.g., AB1234)"
    required
  />
  <input type="submit" value="Submit" />
</form>

In this case, the product code must consist of two letters followed by four digits.

Dynamic Pattern with JavaScript

While the pattern attribute is typically static, you can dynamically modify it using JavaScript for more complex validation scenarios.

<form>
  <label for="dynamicInput">Dynamic Input:</label>
  <input type="text" id="dynamicInput" name="dynamicInput" required />
  <input type="submit" value="Submit" />
</form>

<script>
  const dynamicInput_script = document.getElementById("dynamicInput");
  dynamicInput_script.addEventListener("input", function () {
    // Example: Validate for even number of characters
    if (this.value.length % 2 === 0) {
      this.pattern = ".{"+this.value.length+"}"; // Any Character repeated by length of input
      this.title = "Enter an even number of characters";
    } else {
      this.pattern = ".{"+this.value.length+"}"; // Any Character repeated by length of input
      this.title = "Enter an odd number of characters";
    }
  });
</script>

In this example, the pattern attribute is dynamically updated based on the length of the input value, ensuring it contains an even number of characters.

Note: Dynamic patterns offer flexibility but should be used judiciously to avoid overly complex client-side validation. 🔑

Real-World Applications of the pattern Property

The pattern property is beneficial in various scenarios, including:

  • E-commerce: Validating product codes, credit card numbers, and zip codes.
  • User Registration: Enforcing username and password formats.
  • Data Entry Forms: Ensuring data adheres to specific organizational standards.
  • Surveys: Validating open-ended responses to conform to length or format requirements.

Browser Support

The pattern attribute is supported by all major modern browsers, ensuring consistent validation across different platforms.

Note: Always test your forms in multiple browsers to ensure consistent behavior and user experience. 🌐

Conclusion

The HTML pattern attribute provides a powerful and convenient way to validate user input against regular expressions. By leveraging this attribute, you can enforce specific data formats, enhance data integrity, and improve the overall user experience. From basic format validation to more complex scenarios, the pattern attribute is an indispensable tool for web developers.