HTML Search Input pattern Attribute: Validating Search Input with Regular Expressions

The HTML search input field, defined using <input type="search">, is designed for entering search queries. To enhance validation and ensure that users enter data in a specific format, you can use the pattern attribute. The pattern attribute specifies a regular expression that the input’s value must match to be considered valid. This guide will provide a comprehensive overview of the pattern attribute, its syntax, and practical examples to help you effectively use it in your web forms.

What is the pattern Attribute?

The pattern attribute is a constraint applied to an <input> element that uses regular expressions to define valid data formats. When a form is submitted, the browser checks whether the value of the input field matches the specified pattern. If the pattern does not match, the form will not submit, and an error message may be displayed, prompting the user to correct the input.

Syntax

The syntax for using the pattern attribute is as follows:

<input type="search" id="searchPattern" name="search" pattern="regexp" title="description">

Here:

  • pattern="regexp": Specifies the regular expression pattern that the input value must match.
  • title="description": Provides a descriptive message to the user about the expected format, which is often displayed when the input fails validation.

Attributes Table

| Attribute | Type | Description |
| :——– | :—– | :—————————————————————————————————— |
| pattern | String | A regular expression that the input element’s value is checked against. |
| title | String | A descriptive message that provides guidance to the user about the expected format when validation fails. |

Examples

Let’s explore several examples of how to use the pattern attribute with different regular expressions to validate search input.

Basic Numeric Pattern

This example validates that the search input contains only numbers.

<form>
  <label for="numericSearch">Numeric Search:</label>
  <input
    type="search"
    id="numericSearch"
    name="numericSearch"
    pattern="[0-9]+"
    title="Only numbers are allowed."
  />
  <input type="submit" value="Submit" />
</form>

In this case, the pattern [0-9]+ ensures that the input value consists of one or more digits.

Alphanumeric Pattern

This example validates that the search input contains only alphanumeric characters (letters and numbers).

<form>
  <label for="alphanumericSearch">Alphanumeric Search:</label>
  <input
    type="search"
    id="alphanumericSearch"
    name="alphanumericSearch"
    pattern="[a-zA-Z0-9]+"
    title="Only alphanumeric characters are allowed."
  />
  <input type="submit" value="Submit" />
</form>

The pattern [a-zA-Z0-9]+ allows both uppercase and lowercase letters, as well as numbers.

Custom String Pattern

This example validates that the search input matches a specific string format, such as starting with “ID-” followed by numbers.

<form>
  <label for="customStringSearch">Custom String Search:</label>
  <input
    type="search"
    id="customStringSearch"
    name="customStringSearch"
    pattern="ID-[0-9]{3}"
    title="Please enter in the format ID- followed by three numbers (e.g., ID-123)."
  />
  <input type="submit" value="Submit" />
</form>

The pattern ID-[0-9]{3} requires the input to start with “ID-“, followed by exactly three digits.

Email Pattern

Although <input type="email"> is available for email validation, you can also use the pattern attribute to specify a custom email format.

<form>
  <label for="emailSearch">Email Search:</label>
  <input
    type="search"
    id="emailSearch"
    name="emailSearch"
    pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}"
    title="Please enter a valid email address."
  />
  <input type="submit" value="Submit" />
</form>

The pattern [a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,} validates a basic email format, ensuring there is an @ symbol and a domain with at least two characters after the dot.

Live Validation Example

To provide real-time feedback to users, you can combine the pattern attribute with JavaScript to validate the input as the user types.

<form>
  <label for="liveValidationSearch">Live Validation Search:</label>
  <input
    type="search"
    id="liveValidationSearch"
    name="liveValidationSearch"
    pattern="[A-Za-z]{3,10}"
    title="Enter a word with 3 to 10 letters"
    oninput="validateInput()"
  />
  <span id="validationMessage"></span>
  <input type="submit" value="Submit" />
</form>

<script>
  function validateInput() {
    const inputField_live = document.getElementById("liveValidationSearch");
    const validationMessage_live = document.getElementById("validationMessage");

    if (inputField_live.checkValidity()) {
      validationMessage_live.textContent = "Valid input!";
      validationMessage_live.style.color = "green";
    } else {
      validationMessage_live.textContent = inputField_live.title;
      validationMessage_live.style.color = "red";
    }
  }
</script>

In this example, the validateInput() function checks the validity of the input field whenever the user types, providing immediate feedback.

Using the title attribute

The title attribute’s main role is to provide a helpful message when the input doesn’t match the pattern. However, you can use JavaScript to display the validity state of the input using the title attribute.

<form>
  <label for="titleValidationSearch">Search with Title Validation:</label>
  <input
    type="search"
    id="titleValidationSearch"
    name="titleValidationSearch"
    pattern="[A-Za-z]{5,}"
    title="Please enter at least 5 letters."
    oninput="checkValidityTitle()"
  />
  <span id="titleValidationMessage"></span>
  <input type="submit" value="Submit" />
</form>

<script>
  function checkValidityTitle() {
    const inputField_title = document.getElementById("titleValidationSearch");
    const messageSpan_title = document.getElementById("titleValidationMessage");

    if (!inputField_title.checkValidity()) {
      messageSpan_title.textContent = inputField_title.title;
      messageSpan_title.style.color = "red";
    } else {
      messageSpan_title.textContent = "Input is valid!";
      messageSpan_title.style.color = "green";
    }
  }
</script>

In this setup, the checkValidityTitle() function checks the validity of the input field and displays the message from the title attribute if the input is invalid.

Tips and Notes

  • Provide Clear Instructions: Always include the title attribute to inform users about the expected format.
  • Test Regularly Expressions: Regular expressions can be complex, so test them thoroughly to avoid unexpected behavior.
  • Consider Accessibility: Ensure that error messages and instructions are accessible to all users, including those using assistive technologies.
  • Server-Side Validation: Always perform server-side validation in addition to client-side validation to ensure data integrity and security.

Real-World Applications

  1. Product ID Validation: Validating that product IDs entered by users match a specific format.
  2. ZIP Code Validation: Ensuring that ZIP codes are entered in the correct format (e.g., five digits or five digits followed by a hyphen and four digits).
  3. Username Validation: Enforcing specific rules for usernames, such as minimum length and allowed characters.
  4. Search Query Formatting: Validating that search queries adhere to specific guidelines, such as requiring certain keywords.

Browser Support

The pattern attribute is supported by all modern browsers.

Conclusion

The pattern attribute provides a powerful and flexible way to validate search input in HTML forms. By using regular expressions, you can define precise validation rules that ensure users enter data in the correct format. Combining the pattern attribute with JavaScript for live validation can further enhance the user experience by providing immediate feedback. Always remember to supplement client-side validation with server-side validation for robust data integrity.