70 of 133 menu

The pattern attribute

The pattern attribute specifies validation of the HTML form input field against a regular expression.

Regular expressions are special commands that allow you to create almost any validation rules. You can learn more about them in PHP Regular Expressions Book or JavaScript Regular Expressions Book.

When attempting to submit a form if the field with this attribute is not filled in, the browser will not allow the form to be submitted and will display an error in the form of a pop-up hint. Unfortunately, the error text and its appearance cannot be changed using HTML or CSS.

Please note that the presence of the pattern attribute does not exempt you from checking the correctness of the form filling on the server side in PHP (since protection via the attribute is easy to bypass).

The pattern attribute should be applied to the input or textarea tags.

Example

Let's turn to the tag input and add the attribute pattern, into which we will put a regular expression that checks that a two-digit number is entered into the input (for example, 25).

Enter any number and try to click the button to submit the form. If the number entered is not two digits, the browser will not allow you to submit the form and will display an error message, otherwise the form will be submitted:

<form action=""> <input type="text" pattern="\d{2}"> <input type="submit"> </form>

:

Example . Empty field

In the previous example, the browser only returned an error if the field was not empty (although an empty field is not a two-digit number). Let's try to make it so that the error is returned for an empty field too - together with the pattern attribute, we'll also write the required attribute:

<form action=""> <input type="text" pattern="\d{2}" required> <input type="submit"> </form>

:

See also

  • attribute required,
    with which you can check for emptiness
byenru