The pattern attribute is a small instruction attached to an HTML element. Its job is to javaScript-style regular expression for text field constraint. It is easier to remember when you can see it in a real piece of markup.
What pattern is used for
JavaScript-style regular expression for text field constraint. The attribute appears inside an element’s opening tag. Depending on its definition, it may take a specific string, a number, an enumerated keyword, or be a boolean attribute.
The example below uses it in a input context. Other elements may support it too, or may give the same attribute a different meaning.
Example you can try
<form action="/save" method="post">
<label for="example-field">Example pattern</label>
<input id="example-field" name="example_field" type="text" pattern="[A-Z]{3}[0-9]{2}">
<button type="submit">Save</button>
</form>
How the example works
Look for pattern in the snippet. Here the example shows the value [A-Z]{3}[0-9]{2}. This is a concrete input the browser can interpret; it is not just text shown to the reader.
A pattern is used for compatible text-like inputs and is evaluated as a full-value match using JavaScript-style regular expression rules.
Values and important behavior
For text-like inputs, browsers treat the regular expression as if it must match the entire value. Prefer friendly instructions and server-side checks.
This detail matters most when the page receives user input, navigates to another document, or loads an external resource. In those cases, check the browser behavior and any server-side requirements separately.
Small practice task
Copy the code and change pattern to another sensible value, or remove it entirely if it is optional. Test the difference in the browser and inspect any submitted value or network request.
Common Beginner Mistakes
- A pattern is used for compatible text-like inputs and is evaluated as a full-value match using JavaScript-style regular expression rules.
- Using
patternon an element that does not support it. - Believing that an HTML hint or client-side check replaces real server validation or a security policy.
Key Takeaways
patternis used to javaScript-style regular expression for text field constraint.- A pattern is used for compatible text-like inputs and is evaluated as a full-value match using JavaScript-style regular expression rules.
- Choose valid values and test the result instead of guessing what the browser will do.