Validate email addresses using regex and advanced checks
1// Simple email validation
2function isValidEmail(email) {
3 const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
4 return regex.test(email);
5}
6
7// More strict email validation
8function isValidEmailStrict(email) {
9 const regex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
10 return regex.test(email);
11}
12
13// Validate with additional checks
14function validateEmail(email) {
15 // Basic format check
16 if (!isValidEmailStrict(email)) {
17 return { valid: false, error: 'Invalid email format' };
18 }
19
20 // Check length
21 if (email.length > 254) {
22 return { valid: false, error: 'Email too long' };
23 }
24
25 // Check local part length (before @)
26 const [localPart] = email.split('@');
27 if (localPart.length > 64) {
28 return { valid: false, error: 'Local part too long' };
29 }
30
31 return { valid: true };
32}
33
34// Usage examples
35console.log(isValidEmail('test@example.com')); // true
36console.log(isValidEmail('invalid.email')); // false
37console.log(validateEmail('test@example.com')); // { valid: true }Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.