Back to library
🛠️Utilitiesjavascriptbeginner

Email Validation

Validate email addresses using regex and advanced checks

validationemailregex

Code

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 }

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.