|
1 | | -## Email Address Validation |
| 1 | +# Email Address Validation |
2 | 2 |
|
3 | | -This regular expression checks if the provided string matches the common pattern for email addresses. |
| 3 | +This project provides email validation functionality in pure JavaScript. It includes a refactored regex implementation that covers common RFC 5322 patterns and stricter domain rules. |
4 | 4 |
|
5 | | -**Please note that the code is based on ES2021, and as such, will not work in the global scope or scopes that are not ES2021 compatible.** |
| 5 | +--- |
6 | 6 |
|
7 | | -^[a-zA-Z0-9._%+-]+: Matches one or more characters that can be letters (both uppercase and lowercase), digits, dots, underscores, percent signs, or plus or hyphen signs at the start of the string. |
8 | | -@: Matches the "@" symbol. |
9 | | -[a-zA-Z0-9.-]+: Matches one or more characters that can be letters, digits, dots, or hyphens in the domain part of the email address. |
10 | | -\.: Matches a dot. |
11 | | -[a-zA-Z]{2,}$: Matches two or more letters at the end of the string, representing the top-level domain (TLD) of the email address. |
| 7 | +## Refactored Email Validation (2025 Update) |
| 8 | + |
| 9 | +The regex has been improved to handle edge cases in the local part, domain, and top-level domain (TLD). |
| 10 | + |
| 11 | +### Key Features |
| 12 | + |
| 13 | +- Supports letters, digits, and allowed special characters in the local part: |
| 14 | + `!#$%&'*+/=?^_`{|}~-` |
| 15 | +- Supports dots in the local part, but not consecutive dots. |
| 16 | +- Supports quoted local parts, e.g., `"john.doe"@example.com`. |
| 17 | +- Validates domain labels: |
| 18 | + - Letters, digits, and hyphens (`-`) |
| 19 | + - Labels cannot start or end with a hyphen |
| 20 | + - No consecutive dots |
| 21 | +- Restricts TLD length to 2–63 characters. |
| 22 | +- Supports IPv4/IPv6 literals in brackets, e.g., `user@[192.168.0.1]`. |
| 23 | + |
| 24 | +### Example Usage |
| 25 | + |
| 26 | +```js |
| 27 | +const emailRegex = /^(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:(?:\\[\x00-\x7f]|[^\\"\r\n])*)")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}|\[(?:(?:25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})\.){3}(?:25[0-5]|2[0-4][0-9]|1?[0-9]{1,2}|[a-zA-Z0-9-]*[a-zA-Z0-9]:[^\]]+)\])$/; |
| 28 | + |
| 29 | +function validateEmail(email) { |
| 30 | + return emailRegex.test(email); |
| 31 | +} |
| 32 | + |
| 33 | +const emails = [ |
| 34 | + "example@email.com", |
| 35 | + "user.name+tag@example.co.uk", |
| 36 | + '"quoted.user"@example.com', |
| 37 | + "user@[192.168.1.1]", |
| 38 | + "user@-example.com", |
| 39 | + "user@example..com", |
| 40 | + "user@example-.com", |
| 41 | + "user@.example.com" |
| 42 | +]; |
| 43 | + |
| 44 | +emails.forEach(email => { |
| 45 | + console.log(email, validateEmail(email) |
| 46 | + ? "is valid" |
| 47 | + : "is invalid"); |
| 48 | +}); |
0 commit comments