Validating information before users submit a form is essential to ensure that the data entered is correct and conforms to what we expect to receive as web developers. HTML5 provides us with a powerful tool for form validation: the attribute patterns
. This attribute allows us to define a regular expression (regex) against which the field value will be checked before the form is submitted. In this post, we will explore how to use this attribute to improve the user experience and avoid common mistakes.
Table of Contents
ToggleWhat is a Regular Expression and How is it Applied in the Pattern Attribute?
A regular expression, or regex, is a sequence of characters that forms a search pattern. It allows you to recognize text strings that match that defined pattern. For example, if we want to validate a phone number, email address, or even a zip code, we can do it using regex.
The attribute patterns
in HTML accepts a regex as its value and can be applied to input fields () with types such as 'text', 'date', 'email', among others. When a user tries to submit a form with a field that has an attribute
patterns
, the browser will verify that the entered value fits the defined pattern. If not, the form submission will be blocked and a message will be displayed asking the user to correct the entry.
Implementing Basic Validations with Pattern
To start, let's look at some simple examples of how to use the attribute patterns
.
Validating a Phone Number
Suppose we want to ensure that a phone number has a specific format: 3 digits, a hyphen, 3 more digits, another hyphen, and 4 digits (XXX-XXX-XXXX).
Here, d
represents a digit (0-9), and the keys {}
indicate the number of times that digit must be repeated.
Validating an Email Address
Just as there are default regex for certain fields like type="email"
, patterns
It offers us even more control. If we wanted more specific validation, such as only accepting emails with specific domains (example.com), we could write:
This pattern looks for a series of allowed characters followed by @example.com
, ensuring that the domain is exactly what you want.
Advanced Use of the Pattern Attribute
Let's move on to more complex scenarios where validations become more detailed and specific.
Secure Passwords
When we want a password to meet certain security requirements, at least one number, one uppercase letter, one lowercase letter, and one special character, all in a length of at least 8 characters, patterns
comes to the rescue:
Postal Codes and Regionalized Formats
Each country has its own format for postal codes. If we are developing for a specific audience, we can adjust the pattern to meet those standards. Take, for example, a standard US zip code (5 digits or 5+4 format):
Improving User Experience with Custom Error Messages
One of the most important aspects when implementing validations is to ensure that error messages are clear and useful to users. Although the attribute title
helps us provide a guiding message, we can also enhance the feedback using JavaScript to further personalize these messages.
const inputs = document.querySelectorAll('input[pattern]'); for(let input of inputs){ input.addEventListener('invalid', function(event){ event.preventDefault(); // Here we can customize the error message if(!event.target.validity.patternMismatch){ / / Show a different error message if the validation has a problem other than pattern }else{ // Custom message for pattern validation input.setCustomValidity('Please follow the specified format.'); input.addEventListener('input', function(event){ // Clear custom validation input.setCustomValidity(''); }); }
In this code, we use the event invalid
to intercept a validation error and then we apply setCustomValidity
to define a custom error message. Every time the user modifies the content of the field, the message is reset to allow a new validation.
Conclusions
The use of the attribute patterns
in HTML is a powerful and efficient way to validate data in web forms. It not only ensures that data is in the proper format before being sent to the server, but also improves the user experience by preventing incorrect submissions. By relying on regular expressions as a base, this validation method offers great flexibility to adapt to multiple formats and situations.
Form validation is just one aspect of web development. For more tips and tricks, be sure to visit NelkoDev and explore other resources. And if you have any questions or would like to discuss more specific customizations, feel free to get in touch via NelkoDev Contact.
Validating effectively is essential for any successful web application, and the patterns
It is a tool that should not be missing in your web development toolbox. Practice your implementation, try different patterns, and create forms that are as robust as they are user-friendly.