Attribute pattern

Telling the browser what the value of form fields should be.

Time to read: less than 5 min

Briefly

The pattern attribute contains a regular expression that the entered value in <input> must match.

Example

In this example, the browser will check before submitting the form that the password is at least 6 characters long:

        
          
          <form>  <input type="password" pattern=".{6,}">  <button>Submit</button><form>
          <form>
  <input type="password" pattern=".{6,}">
  <button>Submit</button>
<form>

        
        
          
        
      

How it is written

The pattern attribute can only be applied to <input> tags and only with the following attribute values for type:

  • text;
  • tel;
  • email;
  • url;
  • password;
  • search.

The value must be a regular expression that the browser will use to check what is entered in the field before submitting the form. If the value does not match the regular expression, the browser will show a pop-up tooltip with an error. The error mechanism will only work when submitting the field from a "real" form with the <form> tag; without a form, you will have to check the field yourself.

The text of the pop-up tooltip can be supplemented using the title attribute. Most browsers will show this text along with the error. In the example below, in addition to the standard text, the tooltip will say "At least 6 characters".

        
          
          <label>  Create a password:  <input type="password" pattern=".{6,}" title="At least 6 characters"></label>
          <label>
  Create a password:
  <input type="password" pattern=".{6,}" title="At least 6 characters">
</label>

        
        
          
        
      
Tooltip in Google Chrome

In practice

Advice 1

🛠 It's better not to write overly strict patterns for value validation. You can never anticipate all possible scenarios. For example, on many websites, forms are set up in such a way that I cannot enter my name using Ё. The regular expression does not specify that this is an allowed character. Check only what is truly necessary. For example, to validate an email, it is sufficient to check that there is a @ symbol in the text.