DEV Community

loading...
Cover image for JS: Check if an email is valid

JS: Check if an email is valid

devlorenzo profile image DevLorenzo Updated on ・2 min read

Hello World! The sixth episode of the series - A CSS/JS trick in 5 minutes.
My first ever Dev.to article was about HTML forms, in the last part, I explained you how to check if an email is valid. I will do the same here while going a little bit deeper.


First We have to know how emails are done. In big lines, we know that their divided into two parts and always contain @. This w3 resource explains that better.

A base solution can be:

function checkEmailValidity (email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
}
Enter fullscreen mode Exit fullscreen mode

This function will just check if the email contains one (and doesn't contain more) @. This is better when you want to be inclusive (you think it's better to have some fake email while annulling the possibility to reject the right ones).

We have to use regex to know if the email is valid, if you don't know how they work, check this:

A JavaScript Regular Expression (or Regex) is a sequence of characters that we can utilize to work effectively with strings. Using this syntax, we can search for text in a string, replace substrings in a string or extract information from a string.
Check this cool article to learn more about regex.


We could also use a more advanced regex to check other parameters such as first character, unallowed characters, or invalid domain names:

function checkEmailValidity (email) 
{
 if (/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(myForm.emailAddr.value))
  {
    return (true)
  }
    return (false)
}
Enter fullscreen mode Exit fullscreen mode

If you need it I also did an article on how to check if a password is valid.

Hope this helped and thanks for reading!

Please smash that like button to make me understand that you want the series to continue :)


Subscribe to my Newsletter!

A loooong, and fun, weekly recap for you
Free PDF version of my articles
Highly customizable inbox
That's --> free <-- and you help me!

Discussion (10)

pic
Editor guide
Collapse
andrewbridge profile image
Andrew Bridge

It's probably worth sharing this StackOverflow link: How to validate an email in Javascript

The specific answer linked suggests:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Enter fullscreen mode Exit fullscreen mode

...as the most complete answer, meeting the full RFC spec, though it caveats that with reasons why not to use it.

You'd be far better off not validating an email with JS at all and instead using <input type="email" /> to provide immediate user feedback and, of course, strong validation on the server receiving the input. You can still style your inputs based on valid and invalid input and the validation is done for you!

Collapse
mellen profile image
Matt Ellen

It doesn't completely comply to the RFC, as the RFC allows for comments and the regex does not. As one would expect with a regex.

Collapse
andrewbridge profile image
Andrew Bridge

Haha, so even with 321 characters of regex it's not entirely complete.

To be clear, I'm only making the assumption that <input type="email" /> will validate perfectly to the RFC. But I'd rather leave it to a natively supplied tag than write my own either way.

Thread Thread
mellen profile image
Matt Ellen • Edited

I agree. The tag is tested by millions of people, everyday, so if there were errors they would pop up.

On the other hand, I don't see the utility of comments in email addresses.



matt (this is a comment 
(with a nested comment) 
which is patently useless)  .ellen@example.com
Enter fullscreen mode Exit fullscreen mode
Thread Thread
andrewbridge profile image
Andrew Bridge

Someone, somewhere makes heavy use of comments in email addresses I bet. That one person would be positively peeved if we broke their workflow 😆

Collapse
inhuofficial profile image
InHuOfficial • Edited

Not bad but it will miss the edge cases:

For example

valid

firstname+lastname@example.com: valid ✔
email@example.museum: valid ✔
firstname-lastname@example.com: valid ✔
email@123.123.123.123: valid ✔

invalid

#@%^%#$@#$@#.com: not valid ✔
email@-example.com: valid ❌
email@example..com: not valid ✔
Abc..123@example.com: valid ❌
email..email@example.com: valid ❌

Tested here: jsfiddle.net/za5cs1rh/1/

May I suggest:-

function cev(email) 
{
 if (/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/.test(email))
  {
    if(email.indexOf("..") == -1){
        return email + ": valid";
    }
  }
    return email + ": not valid";
}
Enter fullscreen mode Exit fullscreen mode

A bit longer and still not 100% perfect but much closer. Also someone smarter than me can probably adjust the regex to include the check for a double full stop / period as I have to check that separately which makes the function untidy!

Tested here: jsfiddle.net/za5cs1rh/2/

With that being said even Google Chrome things some of those that aren't valid are valid so I suppose it doesn't matter!

Collapse
dwd profile image
Dave Cridland

I used to work for the team that designed MIXER, which gateways X.400 mail through to Internet Mail, so had to deal with horrors like "/C=GB/O=Isode Ltd/CN=Steve Kille"@mixer.isode.com and now can't even consider the concept of email address validation.

To add further confusion, that email address is not case-insensitive - the "local part" before the @-sign is case-sensitive, whereas the domain (as per RFC) can be case-folded safely.

And, of course, EAI makes everything even more confusing, with Unicode throughout.

As an interesting (possibly) aside, when the XMPP world borrowed the fundamental syntax of local@domain for its addresses (known as "Jids"), it didn't borrow all of the byzantine email syntax - instead it has canonicalization and normalization, and a highly restricted syntax - so restrictive it's actually as simple as most people's idea of email address syntax...

Collapse
lukeshiru profile image
△ LUKE知る

Niche thing:

There is no point in structures like this:

function example (string) {
  if (string.test(/./gu)) {
    return true;
  }
  return false;
}
Enter fullscreen mode Exit fullscreen mode

String.prototype.test already returns a boolean, so is almost like saying:

"if x is true then return true, if not then return false"

Instead of just returning x. This is far better:

const example = string => string.test(/./gu);
Enter fullscreen mode Exit fullscreen mode
Collapse
mellen profile image
Matt Ellen

The full spec for valid email addresses allows for comments in the email address! It's quite ridiculous. This means that any regular expression is not sufficient to comply with the RFC.

RFC5322

Collapse
inhuofficial profile image
InHuOfficial

Oh dear, Today I Learned that some people are insane, who the hell puts comments in an email address??? lol.

Thanks for that Matt, one to add to my bag of useless facts! 🤣