Extend Field Validation with Regular Expressions
When building Drupal websites, you often need specific validation rules for fields. For instance, you might want to ensure users enter only a certain number of characters in a text field, or perhaps you want to accept email addresses exclusively from specific domains. In such cases, regular expression validation provides an elegant solution.
A regular expression (regex) is a powerful search pattern used to match and validate strings. Many programming languages include specialized libraries and functions designed to work with these expressions. PHP, which powers Drupal, offers robust regex support that we can leverage effectively. One straightforward way to implement regex validation in Drupal is through the **Drupal RegEx Field Validation** module.
The RegEx Field Validation module, which supports both Drupal 7 and Drupal 8/9, offers a user-friendly interface for adding validation rules to content type fields. After installation, the module adds these configuration options to every text field in your content types:
- Validate Field with RegEx: A checkbox that enables or disables regex validation. When enabled, it reveals additional configuration options.
- Regular Expression: A textarea where you can enter your validation pattern.
- Error Message: A text field where you can customize the message displayed when validation fails.
While several modules provide field validation capabilities, this module stands out for its simplicity and focused functionality. It's actively maintained and available for both Drupal 7 and Drupal 8/9 versions.
Here are some practical regex patterns you can use:
^[^<]{0,100}$
Validates text containing between 0 and 100 characters.
^[AaBb]$
Validates exactly one character: A, a, B, or b.
^(http|https):\/\/.{2,80}$
Validates URLs starting with "http" or "https", containing between 2 and 80 characters.
^.{2,40}@.{2,50}\.[a-zA-Z]{2,5}$
Validates email addresses with 2-40 characters before "@", 2-50 characters for domain name, and 2-5 letters for top-level domain.
^(ABC|DEF|GHI|JKL|MNO|PQR|STU|VWX)?$
Validates three-letter strings from the specified list.
^([0-9]+(\.[0-9]{2})?)?$
Validates numbers with optional two decimal places (e.g., 29.99).
^[0-9.]{1,8}$
Validates numerical values between 1 and 8 digits.
^[^<\x09\x0a\x0d]{0,10}$
Validates single-line text between 0 and 10 characters, excluding HTML markup.
^[^<]{0,100}$
Validates multi-line text between 0 and 100 characters, excluding HTML markup.
^[^<\x09\x0a\x0d]{0,1000}$
Validates text containing between 0 and 1000 characters, excluding HTML markup.
These regular expressions provide a solid foundation for common validation scenarios in Drupal. Remember to test your patterns thoroughly before implementing them in a production environment.