How use the pattern attribute to validate forms using Regular Expressions in HTML5
- 👤 Andrés Cruz
Form validation has always been part of the “dark art” of web development. Before HTML5, I myself went through that era where you had to battle with JavaScript, invent your own events, and pray that every browser interpreted the rules the same way. Today, fortunately, the story is very different: thanks to the pattern attribute, we can validate forms directly from HTML using regular expressions, without external libraries and without headaches.
In this guide, I tell you how pattern really works, how to combine it with powerful regular expressions, and how to avoid the most common errors I see in many projects (including my own from years ago). Let's go step by step.
If you want to learn how to give forms a good style with CSS when errors occur.
Introduction to Native Validation in HTML5
Why HTML5 simplifies client-side validation
When HTML5 appeared, the first thing I noticed was that I could delegate tasks to the browser that I used to do manually: controlling sizes, formats, data types... and all with attributes like type, required, minlength, maxlength, or pattern. In my case, it was a total relief to stop loading libraries just to validate an email or a username.
The browser does most of the work: it detects errors, displays messages, prevents incorrect submissions, and reacts in real time. Everything is native.
Limitations and the Role of Server Validation
But be careful: something I always repeat (and learned the hard way) is that HTML5 DOES NOT replace server-side validation. Any user can modify the HTML from the browser console or send a fake form pointing directly to your endpoint. Therefore, client-side validation is convenience; server-side validation is security.
What the pattern attribute is and how it works
Inputs compatible with pattern
The pattern attribute works on virtually all text-based inputs:
- text
- search
- url
- tel
- password
- number
- datetime-local, time, week, month
Practically any “writable” field can be validated this way.
How the browser interprets regular expressions
The value of pattern must be a valid regular expression according to the rules of the JavaScript RegExp engine. This includes:
- Correctly escaping ()[]{}/|-
- Unicode matching (modern v flag)
- Support for advanced ranges and classes
Something important that many people don't know: pattern requires the expression to match the ENTIRE value, as if the expression had ^(?: ... )$ by default.
When patternMismatch and validityState are activated
Each input has an internal object called validityState. If the value doesn't match the pattern, validityState.patternMismatch is activated. This is what triggers the :invalid style and the browser's messages.
This is tremendously useful because you don't need to write a single line of JavaScript to detect basic failures.
HTML5 allows us to do a great number of things, among them is the simple and straightforward validation of forms, natively and very friendly, since we use attributes in the fields for that purpose; this saves us a lot of headaches from using external libraries, playing with events and so on, everything is native and practically automated.
Client-Side Validations with HTML5
These validations are NOT a replacement for server-side validations. As the good programmer you surely are, you must know that it is necessary to validate on both sides, especially on the server side, we must always verify the received data; since, being HTML, the user can modify the HTML from the browser's developer console or simply create their own form pointing to our server and destroy or damage our application.
You must be clear that a large part of the validations are carried out with the regular expressions that we explain a little in the next section.
Regular Expressions in HTML5: Key Fundamentals
Essential symbols for creating useful patterns
If you come from using regex in JavaScript, you already have an advantage. Here are the most used symbols:
- . → any character
- [0-9] → digits
- [A-Za-z] → letters
- + → one or more
- * → zero or more
- {n,m} → minimum/maximum length
- | → alternatives
- \. → literal dot
The first few times I tried to validate forms with complex expressions, it was hard to find the exact pattern. Over time I discovered that almost everything can be solved with well-structured ranges and quantifiers.
Complete Match Rules in pattern
Unlike many regex engines, there are no partial matches here. If the pattern says [a-z]{4,8}, anything that doesn't exactly meet that length and character range is invalid.
Common Errors when building patterns
The errors I have seen (and committed) the most:
- Writing slashes /regex/ (they are not used in pattern).
- Forgetting to escape special characters.
- Trying to validate “perfect” emails with gigantic regex.
- Creating overly strict patterns that frustrate the user.
The type attribute to define the data type of the input and other form elements
As we explained in a previous entry, where we talked about the different types of form fields that HTML5 brings us:
The pattern attribute is compatible with the following form inputs:
- password
- search
- tel
- text
- url
- number
- month
- time
- week
- datetime
- datetime-local
A crucial practice that must be carried out obligatorily when developing applications, especially web applications, is to validate the data entered by the user both on the client side and on the server side; with the emergence of JavaScript, it is possible to perform client-side validations and thus avoid multiple calls to the server and saturating it.
What are regular expressions?
Regular expressions are patterns used in multiple applications for searching for specific characters or combinations of them and a subset of the latter is form validation with JavaScript; which, thanks to HTML5, has its own API through the pattern attribute that we can use in forms.
Regular expressions are used to find matches and patterns, that is, to check if it has the desired format and reject or accept it as required; in the case that interests us, for form fields, we can indicate what length, what data types, matches, and which characters it must have and which it must not, and in what positions or range of positions; they are widely used not only for validations but for all types of applications in general and are widely supported by programming languages, including HTML5, which is a basic language for the World Wide Web; you can get more information about it at MDN: Regular Expressions
The problem with native JavaScript validations
Currently there are a large number of web browsers, each with its own conventions, which makes client-side validations through this route difficult; in addition to the fact that this way we do not have to incorporate or develop our own plugins or complements that perform this work.
Validating forms is a fundamental task today, and this is because forms have become the fundamental piece of any application or web page, they are used to obtain all types of information from the user and it is often necessary that this information or data entered by the user has a certain format or organization and this is where validations using JavaScript and the case of our interest, validations using regular expressions that we can configure using a simple attribute and the regular expression for validation, come in.
JavaScript Plugins for data validation and types of validations
There are a large number of libraries, frameworks, or plugins developed by third parties that perform this task of validating user data and many of them with support for the most used web browsers; however, this results in the inclusion of files in the web application and therefore increases the loading time of the site to perform a task as simple as validating the data; thanks to HTML5 it is no longer necessary to use these libraries, it is enough to use regular expressions as we indicated previously.
Although also remember that we must always validate the data on both sides (double validation), at least the data must be validated on the server side since this is the one that processes the data and the fundamental entity for saving user data, remember that the user can bypass using your form and go directly against the server or even manipulate the HTML of the form.
AI as a great tool for generating regular expressions
The problem with regular expressions is that they are abstract, but, thanks to AI we can ask it to help us generate regular expressions of ALL types for our applications and it does it really well, ready to use.
- You can use prompts like, generate a regular expression that validates that it is an email.
- Or that it has a determined link.
- One to remove determined HTML elements.
- And a long etcetera.
Practical Examples of pattern for real forms
Let's look at some typical examples for validation
Validate usernames
Classic example:
<input type="text" pattern="[A-Za-z0-9]{5,40}" required>I myself usually use patterns of this style that I ask AI to create for me and I validate them when I want to avoid strange characters and maintain a reasonable length range.
Validate emails, phone numbers, and URLs
<input type="email" pattern="^[^@\s]+@[^@\s]+\.[^@\s]+$"> <input type="tel" pattern="[0-9]{9}"> <input type="url" pattern="https?://.+">I remember when I tried to validate phone numbers with pure JavaScript and each browser interpreted different inputs... with pattern that was left behind.
Validate strong passwords
<input type="password" pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}" required>Validate dates and custom fields
<input type="text" pattern="\d{4}-\d{2}-\d{2}" placeholder="YYYY-MM-DD">Improve User Experience with Custom Messages
How to use the title attribute correctly
I always recommend accompanying each pattern with a title. This improves accessibility and prevents the user from wondering “what did I do wrong?”.
Replace the native message with setCustomValidity()
When I need friendlier messages, I use:
input.oninvalid = (e) => { e.target.setCustomValidity("The format is not valid. Example: abc123"); };Avoid bad accessibility practices
I avoid relying only on the title, because some screen readers ignore it. The description must be visible.
Style Validations with CSS (:valid and :invalid)
Clear and Accessible Visual Indicators
input:invalid { border-color: red; } input:valid { border-color: green; }When to avoid distracting styles
I learned that changing the input border while the user is typing can generate anxiety. It is best to apply styles only after the field is “touched.”
Pattern vs. JavaScript vs. Server Validation
- When to trust only HTML5
- If the form is simple, HTML5 is enough. Many times I save entire JavaScript functions.
- When to complement with JavaScript
- For dynamic messages, real-time validation, or very complex patterns, JS is still useful.
- Why server validation should always exist
- There is no negotiation here: everything must be validated on the server side. It is a basic security principle.
Recommended Patterns and Table of Common Expressions
Letters, numbers, ranges, and combinations
- Need Pattern
- Only letters [A-Za-z]+
- Only numbers [0-9]+
- Alphanumeric text [A-Za-z0-9]+
- Length range .{5,20}
- Standard Username [A-Za-z0-9_]{4,16}
- Advanced patterns ready to copy
- Case Pattern
- Strong Password (?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*\W).{8,}
- Date YYYY-MM-DD \d{4}-\d{2}-\d{2}
- Postal Code \d{5}
- Simple URL https?://.+
Frequently Asked Questions (FAQ)
- Does Pattern validate the entire value?
- Yes, it always requires a complete match.
- Which inputs support it?
- Almost all text inputs work: email, url, search, tel, password, etc.
- Is it mandatory to use title?
- No, but it is highly recommended.
- Does Pattern replace JavaScript?
- In simple cases, yes. In advanced cases, no.
- Does Safari support pattern?
- Currently yes, although for a while it was incomplete.
Final Conclusions
Validating forms with the pattern attribute is one of the most powerful and simple tools that HTML5 offers. In my experience, it has reduced the amount of code, user errors, and dependence on external libraries. That said: never forget to validate on the server and keep your patterns clear and accessible.
Learn how to customize the form submission URL with formAction
I agree to receive announcements of interest about this Blog.
With the pattern attribute we can perform validations without using JavaScript libraries and without using external libraries, specifically regular expressions as we will see below; We will see how to validate, telephone numbers, ips, emails, texts, numbers,