How to create regular expressions (Regex) for email address validation?
Email validation is important for ensuring that the email addresses you collect are valid and properly formatted. Regular expressions (regex) play a key role in this process by providing a pattern that email addresses entered by users must match when signing the bulk link.
What is a regular expression?
A regular expression, or regex, is a sequence of characters that defines a search pattern. In email validation, the regex pattern specifies the format a valid email address should adhere to.
Basic email validation regex pattern
Here is a simple regex pattern for validating email addresses: ^[a-zA-Z0-9_.±]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$
Let’s break down this pattern:
Parameters | Description |
---|---|
^ | Start of the string. |
[a-zA-Z0-9_.±]+ | One or more characters that can be letters (a-z, A-Z), digits (0-9), underscores (_), dots (.), plus signs (+), or hyphens (-). |
@ | The at symbol, which is required in all valid email addresses. |
[a-zA-Z0-9-]+ | One or more characters that can be letters (a-z, A-Z), digits (0-9), or hyphens (-). This represents the domain name. |
. | The dot character, which is used to separate the domain name from the top-level domain (TLD). |
[a-zA-Z0-9-.]+ | One or more characters that can be letters (a-z, A-Z), digits (0-9), hyphens (-), or dots (.). This represents the TLD. |
$ | End of the string. |
Enhancing email validation with advanced regex
Handling subdomains
To allow for subdomains in the domain part of an email address, the regex pattern should include a group that matches a subdomain followed by a dot, repeated one or more times.
Example: [a-zA-Z0-9.-]+(.[a-zA-Z]{2,})+
This pattern allows for multiple subdomains, such as “subdomain.example.com.”
Validating special characters
To validate special characters in the local part of an email address, include the required special characters inside square brackets. This ensures that the regex pattern matches email addresses containing those characters.
Example: [a-zA-Z0-9.*%±]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}
This pattern allows for special characters like “.”, “”, “%”, “+”, and “-” in the local part of the email address.
Case insensitivity
To make the regex pattern case-insensitive, add the “i” flag at the end of the pattern. This ensures that the pattern matches email addresses regardless of the case of the letters.
Example: ^[a-zA-Z0-9._%±]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$ with the “i” flag.
This pattern allows for case-insensitive matching of email addresses.
We have also published a video tutorial on this topic. Check out the video below: