Sentry Answers>JavaScript>

Email address validation in JavaScript

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:

Click to Copy
"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:

Click to Copy
function validateEmailAddress(address) { return address.includes("@"); }
  • YoutubeHow Sentry.io saved me from disaster
  • ResourcesImprove Web Browser Performance - Find the JavaScript code causing slowdowns
  • SentryJavascript Error Monitoring & Tracing
  • ResourcesJavaScript Frontend Error Monitoring 101
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,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.

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