Email address validation in JavaScript

David Y.

The Problem

What’s the best way to validate an email address in JavaScript?

The Solution

Email address validation is a more complex problem than it may initially appear. The official email address specification in RFC5322 allows a wide range of valid addresses. For example, the address below would be considered valid according to the RFC:

"Jane Doe @ Work"@localserver

This address contains spaces, more than one @ symbol, and no dot in the domain, all of which are highly atypical for email addresses. And we could make it still more complicated by adding non-English characters and even emoji while remaining compliant with the specification.

Furthermore, as email is an open specification with many different implementations, different email providers may implement different requirements for email addresses. For example, "Jane Doe @ Work"@example.com might be valid according to the specification, but impossible to register with certain email providers. The reverse can also be true: for example, the Japanese mobile operator NTT Docomo allows email addresses with multiple consecutive dots, in violation of RFC5322.

Taking all of these factors into account, the best way to validate an email address is to attempt to send an email to it. If the email sends successfully, the address exists. To further verify that the address is connected to an active mailbox, the sent mail should contain a link or code for the user to follow or provide back to the application.

To avoid attempting to send emails to obviously invalid addresses, we can check that the supplied text contains at least one @ symbol using a function like the following:

function validateEmailAddress(address) { return address.includes("@"); }

Get Started With Sentry

Get actionable, code-level insights to resolve JavaScript performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a JavaScript project and note your DSN

  3. Grab the Sentry JavaScript SDK

<script src="https://browser.sentry-cdn.com/7.111.0/bundle.min.js"></script>
  1. Configure your DSN
Sentry.init({ dsn: 'https://<key>@sentry.io/<project>' });

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.