References

Beginner-friendly references for web development, with live, editable examples.

The HTML pattern attribute

Attribute All modern browsers Updated
Quick answer

The HTML pattern attribute specifies a regular expression the value must match to be valid. It is used on the <input> element (text-like types).

Overview

The pattern attribute specifies a regular expression the value must match to be valid. It applies to the <input> element (text-like types).

Add a title describing the expected format — browsers show it when the pattern fails.

Syntax

<input pattern="[0-9]{4}" title="Four digits">

Values

Value
A JavaScript regular expression (without delimiters).

Example

Live example
<input pattern="[0-9]{4}" title="Four digits" placeholder="1234" style="padding:8px;">

Best practices

  • Give every control a <label> so it has an accessible name.
  • Treat client-side constraints as a convenience — always validate again on the server, since they can be bypassed.
  • Choose the most specific input type so users get the right on-screen keyboard and built-in checks.
  • Keep the submitted name and value meaningful for whatever processes the form.

Frequently asked questions

What does the pattern attribute do?
Validates input against a regular expression.
Are HTML form attributes enough for validation?
They give instant feedback, but client-side checks can be bypassed, so always validate on the server too.
Do form controls still need a label?
Yes. Every control needs a <label> for an accessible name, whatever attributes you set.
Which elements use the pattern attribute?
It is an element-specific attribute, used on form controls such as <input>, <select> and <textarea>.