DEV Community

Cover image for How to validate an email address in JavaScript
Tyler McGinnis
Tyler McGinnis

Posted on • Originally published at tylermcginnis.com

How to validate an email address in JavaScript

Email validation is hard. With the vast amount of complex, but valid email addresses that exist today, the only way to truly tell if an email address is valid is to send the email and see if it bounces. With that said, there are a few things we can do on the front end to make the experience better for everyone. In this post we'll talk about few common approaches for validating email addresses in JavaScript.

First, when validating email addresses I believe it's better to error on the permissive side. I'd much rather let pass a few fake email addresses than reject a valid one. Front-end email validation is about figuring out if the syntax is correct, not if the email address is valid. With that said, we'll start off with the most permissive solution and work our way towards the other end.

function emailIsValid (email) {
  return /\S+@\S+\.\S+/.test(email)
}
Enter fullscreen mode Exit fullscreen mode

If you're not familiar with RegEx, /\S+@\S+\.\S+/ is testing for the most basic email address structure, _@_._. That's typically all I ever assume about an email address. If the email the user types in doesn't follow that structure, odds are they made a typo.

One issue with the Regex above is it'll fail on this format: _@_@._. To fix that, we can change up our Regex a bit.

function emailIsValid (email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
}

emailIsValid('tyler@tyler@tylermcginnis.com') // false
emailIsValid('tyler@tylermcginnis.com') // true
Enter fullscreen mode Exit fullscreen mode

That's it. Anything beyond this is going to be too opinionated. You could find some other solutions by googling around but I recommend re-thinking your approach if the above examples don't work for you.

Discussion (11)

Collapse
berslucas profile image
Lucas Bersier

You could also use <input type="email"> if you're targeting not-edge.

I always jump to the RFC-5322 standard regex (emailregex.com/), but the above seems smaller and less complicated for most projects that don't need to 100% cover all cases.

/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
Collapse
seraphicrav profile image
Ravaka Razafimanantsoa

This regular expression does not validate the new top level domains such as https://はじめよう.みんな/index.html

Collapse
mogery profile image
Gergő Móricz

You can use u at the end to do unicode validation too IIRC.

Collapse
deceze profile image
David Zentgraf

Email addresses do in fact allow spaces in the local part. Your regex leads to false negatives. See en.wikipedia.org/wiki/Email_addres.... Though practically speaking you will probably never encounter emails which use this advanced syntax, precisely because developers implement regexen like this which lead to false negatives and make such addresses unusable.

Collapse
darkain profile image
Vincent Milum Jr

Word of advice, never regex for an email address. Check out this article with a list of crazy yet valid email addresses.

hackernoon.com/the-100-correct-way...

Also, the assumption at the beginning about bounced emails isn't valid either. The server may send an unknown email address into a black hole (no bounce), whereas a valid known email address may bounce for reasons such as a full inbox or invalid contents of the mail being sent.

The closest thing you'll get is having the user click a link within the email. But also have the link in plain text as well in case the user agent strips out HTML.

Collapse
moopet profile image
Ben Sinclair

If you're using it as an optional field, why not just have a "send test notification" action available?

If it needs to be valid for any other reason (like proving someone's identity) then it's probably a forlorn hope anyway.

Collapse
phlash909 profile image
Phil Ashby

This - close the loop at the next layer up if possible, typically seen in registration systems that send a confirmation link.

Collapse
camainc profile image
Charles Cherry • Edited on

Your regex doesn't allow for many valid email addresses. Basically just about anything before the "@" symbol (the local part) is allowed. A lot of gmail addresses have the format

some.name@gmail.com

"The local part can be up to 64 characters in length and consist of any combination of alphabetic characters, digits, or any of the following special characters:

! # $ % & ‘ * + – / = ? ^ _ ` . { | } ~

NOTE: The period character (“.”) is valid for the local part subject to the following restrictions:

  • it is not the first or last character
  • two or more consecutive periods"

mailboxvalidator.com/resources/art...

Collapse
fragsalat profile image
Thomas Schlage

There are possibilities to validate if an email exists without sending an email. Your backend can open a socket the the email server of the email address and ask for the address. I'm not 100% sure if there could be a bouncer rule based on the content but it ensures at least that the given email address accepts emails from your server.

Here is an telnet example for this: webdigi.co.uk/blog/2009/how-to-che...

Collapse
phlash909 profile image
Phil Ashby

This probably only works for a few percent of mail servers these days, most will accept any RCPT TO address, wait for the DATA block and then black hole or reply with an error via a separate outbound message. Specifically done to permit more filtering (anti-spam etc.) and to /prevent/ these sorts of validity checks as they are popular with spammers (can't think why :))

Collapse
wuz profile image
Conlin Durbin

First, when validating email addresses I believe it's better to error on the permissive side.

Great advice here! It's always better to fix things on a company side, over making things worse for users. At one of my old jobs, we had some issues with an email regex that wasn't permissive enough - I believe the user had a quotation mark in their email, which is perfectly valid, but we had never seen it before.