Email Validation Regular Expression
A well-formed email address follows a standard format defined by RFC 5322, but practical validation often balances strictness with usability as most allowed patterns in the standard are not allowed in the actual used email clients. A regular expression that supports the full standard would be very complex and unmaintainable. Email addresses consist of a local part and a domain name separated by an @ symbol.
Recommended Solution
Explanation
^- Start of the string.(?!.*..)- Prevents consecutive dots (..).(?!.*.$)- Prevents trailing dots at the end.[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+- The local part before @. Allows valid characters and special symbols.@- The required separator.[a-zA-Z0-9-]+- Domain name. Allows letters, numbers, and hyphens. For more details on domain validation, see the domain validation article.(?:.[a-zA-Z0-9-]+)*- Subdomains. Allows multiple levels like mail.example.com..[a-zA-Z]{2,}- Top-level domain. Requires at least two letters (e.g., .com, .org).$- End of the string.
Implementation
Test Cases
| Email Address | Valid |
|---|---|
| test@example.com | |
| user.name+tag+sorting@example.com | |
| x@example.com | |
| example-indeed@strange-example.com | |
| example@s.example | |
| admin@mailserver1 | |
| abc..def@example.com | |
| .abc@example.com | |
| abc.@example.com | |
| abc.def@example..com | |
| plainaddress | |
| @missingusername.com | |
| missingatsign.com | |
| username@.com | |
| username@sub..com | |
| username@-example.com | |
| username@example-.com |
Basic Validation
For a quick and simple check, you can use a basic regular expression that ensures the presence of an @ symbol and a domain. This is useful for cases where you just need a minimal validation without enforcing strict rules.
Explanation
^- Start of the string.S+- At least one non-whitespace character before `@`.@- The required separator.S+- At least one non-whitespace character for the domain..- A dot before the top-level domain.S+- At least one non-whitespace character for the TLD.$- End of the string.
Implementation
Test Cases
| Email Address | Valid |
|---|---|
| test@example.com | |
| user.name+tag+sorting@example.com | |
| x@example.com | |
| example-indeed@strange-example.com | |
| example@s.example | |
| admin@mailserver1 | |
| abc..def@example.com | |
| .abc@example.com | |
| abc.@example.com | |
| abc.def@example..com | |
| plainaddress | |
| @missingusername.com | |
| missingatsign.com | |
| username@.com | |
| username@sub..com | |
| username@-example.com | |
| username@example-.com |