Try it yourself with our free Regex Tester tool — runs entirely in your browser, no signup needed.

How to Validate email addresses with regex in TypeScript

How to Validate Email Addresses with Regex in TypeScript

Validating email addresses is a crucial step in any application that requires user input, such as registration forms or contact pages. Incorrectly formatted email addresses can lead to lost customers, failed deliveries, and wasted resources. In this article, we'll explore how to use regular expressions (regex) to validate email addresses in TypeScript.

Quick Example

Here's a minimal example that solves the most common use case:

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const email = 'john.doe@example.com';

if (emailRegex.test(email)) {
  console.log('Email is valid');
} else {
  console.log('Email is invalid');
}

This code defines a regex pattern that matches most common email address formats and uses the test() method to validate the input email address.

Step-by-Step Breakdown

Let's walk through the code line by line:

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  • ^ asserts the start of the string.
  • [a-zA-Z0-9._%+-]+ matches one or more alphanumeric characters, dots, underscores, percent signs, plus signs, or hyphens. This matches the local part of the email address (before the @ symbol).
  • @ matches the @ symbol literally.
  • [a-zA-Z0-9.-]+ matches one or more alphanumeric characters, dots, or hyphens. This matches the domain name.
  • \. matches the dot before the top-level domain.
  • [a-zA-Z]{2,} matches the top-level domain (it must be at least 2 characters long).
  • $ asserts the end of the string.
const email = 'john.doe@example.com';
  • This line defines the email address to be validated.
if (emailRegex.test(email)) {
  console.log('Email is valid');
} else {
  console.log('Email is invalid');
}
  • The test() method executes the regex pattern on the input email address and returns true if it matches, or false otherwise.
  • Based on the result, the code logs a message indicating whether the email is valid or not.

Handling Edge Cases

Here are some common edge cases and how to handle them:

Empty/Null Input

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const email = '';

if (emailRegex.test(email)) {
  console.log('Email is valid');
} else {
  console.log('Email is invalid'); // Output: Email is invalid
}

In this case, the regex pattern will not match, and the code will correctly identify the email as invalid.

Invalid Input

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const email = 'invalid_email';

if (emailRegex.test(email)) {
  console.log('Email is valid');
} else {
  console.log('Email is invalid'); // Output: Email is invalid
}

Again, the regex pattern will not match, and the code will correctly identify the email as invalid.

Large Input

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const email = 'very_long_email_address_that_exceeds_the_maximum_allowed_length@example.com';

if (emailRegex.test(email)) {
  console.log('Email is valid');
} else {
  console.log('Email is invalid'); // Output: Email is invalid
}

In this case, the regex pattern will not match, and the code will correctly identify the email as invalid.

Unicode/Special Characters

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const email = 'john.doe+ünicöde@example.com';

if (emailRegex.test(email)) {
  console.log('Email is valid');
} else {
  console.log('Email is invalid'); // Output: Email is invalid
}

In this case, the regex pattern will not match, and the code will correctly identify the email as invalid.

Common Mistakes

Here are three common mistakes developers make when validating email addresses with regex in TypeScript:

Mistake 1: Incorrect Pattern

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+$/; // Missing top-level domain
const email = 'john.doe@example';

if (emailRegex.test(email)) {
  console.log('Email is valid'); // Output: Email is valid ( incorrect )
} else {
  console.log('Email is invalid');
}

Corrected code:

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

Mistake 2: Not Handling Null/Undefined Input

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const email = null;

if (emailRegex.test(email)) {
  console.log('Email is valid'); // Error: Cannot read property 'test' of null
} else {
  console.log('Email is invalid');
}

Corrected code:

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const email = null;

if (email && emailRegex.test(email)) {
  console.log('Email is valid');
} else {
  console.log('Email is invalid');
}

Mistake 3: Not Considering Unicode Characters

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const email = 'john.doe+ünicöde@example.com';

if (emailRegex.test(email)) {
  console.log('Email is valid'); // Output: Email is invalid ( incorrect )
} else {
  console.log('Email is invalid');
}

Corrected code:

const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/u; // Add the 'u' flag for Unicode support

Performance Tips

Here are three practical performance tips for validating email addresses with regex in TypeScript:

  1. Use the u flag for Unicode support: When working with email addresses that may contain Unicode characters, make sure to add the u flag to your regex pattern to enable Unicode support.
  2. Use a single regex pattern: Instead of using multiple regex patterns to validate different parts of the email address, use a single pattern that covers all the rules.
  3. Avoid unnecessary capturing groups: Capturing groups can slow down the regex engine. If you don't need to capture specific parts of the email address, avoid using capturing groups.

FAQ

Q: What is the best regex pattern for validating email addresses?

A: The regex pattern /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ is a good starting point, but you may need to adjust it based on your specific requirements.

Q: How do I handle null or undefined input?

A: Use the && operator to check if the input is null or undefined before attempting to validate it.

Q: Can I use this regex pattern for validating email addresses in other programming languages?

A: While the regex pattern itself is language-agnostic, the syntax and features used may vary between languages. Be sure to check the documentation for your specific language to ensure compatibility.

Q: How do I validate email addresses with international top-level domains?

A: Use the u flag to enable Unicode support and adjust the regex pattern to accommodate international top-level domains.

Q: Can I use this regex pattern for validating email addresses in real-time?

A: Yes, but be aware that regex patterns can be computationally expensive. Consider using a more lightweight validation approach for real-time validation.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp