DEV Community

loading...
Cover image for 4 Ways to Validate an Email with JavaScript 📮

4 Ways to Validate an Email with JavaScript 📮

Gaël Thomas
I share tips & resources about web programming. 👨‍💻 In love with JS and TypeScript. ✨ Plant addict. 🪴
Originally published at herewecode.io Updated on ・4 min read

In this article, you will discover three ways to do an email validation with JavaScript!

"An old myth says that you are a web development wizard once you create a contact form! 🧙😄" - Unknown

Email validation using Regular Expressions

The most common way to validate an email with JavaScript is to use a regular expression (RegEx). Regular expressions will help you to define rules to validate a string.

If we summarize, an email is a string following this format:

1. First part of an email

  • uppercase and lowercase letters: a-z and A-Z
  • digits: 0-9
  • hyphens: - (not the last or first character)
  • dots: . (not the last or first character)

Note: Some email providers allows email adresses with these character: ! # $ % & ‘ \* + / = ? ^ \ _ \ { | } ~ " ( ) , : ; < > @ [ \ ]. It will depends if you want to accept these mails, but most website rejects them.

2. Second part of an email

  • uppercase and lowercase letters: a-z and A-Z
  • digits: 0-9
  • hyphens: - (not the last or first character)

3. Third part of an email

  • uppercase and lowercase letters: a-z and A-Z
  • digits: 0-9
  • dots: . (not the last or first character)

Here is an email regex expression:

/^[a-zA-Z0-9][\-_\.\+\!\#\$\%\&\'\*\/\=\?\^\`\{\|]{0,1}([a-zA-Z0-9][\-_\.\+\!\#\$\%\&\'\*\/\=\?\^\`\{\|]{0,1})*[a-zA-Z0-9]@[a-zA-Z0-9][-\.]{0,1}([a-zA-Z][-\.]{0,1})*[a-zA-Z0-9]\.[a-zA-Z0-9]{1,}([\.\-]{0,1}[a-zA-Z]){0,}[a-zA-Z0-9]{0,}$/i
Enter fullscreen mode Exit fullscreen mode

In JavaScript, you can use this function for your email validation.

function isEmailValid(email) {
  const emailRegexp = new RegExp(
    /^[a-zA-Z0-9][\-_\.\+\!\#\$\%\&\'\*\/\=\?\^\`\{\|]{0,1}([a-zA-Z0-9][\-_\.\+\!\#\$\%\&\'\*\/\=\?\^\`\{\|]{0,1})*[a-zA-Z0-9]@[a-zA-Z0-9][-\.]{0,1}([a-zA-Z][-\.]{0,1})*[a-zA-Z0-9]\.[a-zA-Z0-9]{1,}([\.\-]{0,1}[a-zA-Z]){0,}[a-zA-Z0-9]{0,}$/i
  )

  return emailRegexp.test(email)
}

console.log(isEmailValid('helloitsme@herewecode.io')) // true
console.log(isEmailValid('hello-its-me@herewecode.io')) // true
console.log(isEmailValid('hello.its.me@herewecode.io')) // true
console.log(isEmailValid('helloitsme+test@herewecode.io')) // true
console.log(isEmailValid('.helloitsme@herewecode.io')) // false
console.log(isEmailValid('helloitsme.@herewecode.io')) // false
console.log(isEmailValid('@herewecode.io')) // false
console.log(isEmailValid('helloitsmeherewecode.io')) // false
console.log(isEmailValid('helloitsme@herewecode')) // false
console.log(isEmailValid('d@d.o')) // false
Enter fullscreen mode Exit fullscreen mode

Note: As you can imagine, this Regex isn't homemade. I found it on Stack Overflow; then, I updated it to match the email string format explained above.

Email validation using an Email Validator

If you don't want to create a custom function to validate emails, you can use libraries.
When we type: "email validation library javascript" on Google, the first result is the "email validator" library.

Here is an example of how to use it:

const validator = require('email-validator')

console.log(validator.validate('helloitsme@herewecode.io')) // true
console.log(validator.validate('hello-its-me@herewecode.io')) // true
console.log(validator.validate('hello.its.me@herewecode.io')) // true
console.log(validator.validate('helloitsme+test@herewecode.io')) // true
console.log(validator.validate('.helloitsme@herewecode.io')) // false
console.log(validator.validate('helloitsme.@herewecode.io')) // false
console.log(validator.validate('@herewecode.io')) // false
console.log(validator.validate('helloitsmeherewecode.io')) // false
console.log(validator.validate('helloitsme@herewecode')) // false
console.log(validator.validate('d@d.o')) // false
Enter fullscreen mode Exit fullscreen mode

Email validator is one library among others. You can find a lot of them with different features online.

Email validation using HTML5 input validation

The last way to validate an email is to use an HTML5 email input.

<input type="email" id="email" name="email" placeholder="email" />
Enter fullscreen mode Exit fullscreen mode

Here is an example of an email validation using a simple form:

<!DOCTYPE html>
<html>
  <body>
    <h1>JavaScript Validate Email</h1>

    <p>Write your email and we will validate it:</p>

    <form>
      <input type="email" id="email" name="email" placeholder="Email" />
      <input type="submit" value="Submit" />
    </form>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Email validation using a form with an HTML5 email input

As you can see, HTML triggers an error when the email address isn't correct. However, if we type, for example: "helloitsme@herewecode" or "-herewecode.io", the form is valid.
This option is a good feature that you should use when you implement a form on your website. It's suitable for a first validation, but don't forget to validate yourself to avoid issues.

Email validation using an API

As a bonus, you can validate emails using APIs. Here are some companies proposing email validation APIs: SendGrid, MailBoxLayer, Abstract API, etc.
Most of these APIs are not free, but they will provide you some advanced features (ex: check if an email exists).

Hey, you did it!

Thanks for reading until the end! I hope you learned from it! 🎉


➡️ I help web developers improve their skills 💻 If you want to get more tips and resources about web programming -> Follow me on my Twitter 🐦

Discussion (4)

Collapse
manuelricci profile image
Manuel Ricci

I suggest to check even the code of the package the author linked. The approach is really interesting

Collapse
gaelgthomas profile image
Gaël Thomas Author

Thanks for sharing that! 😊 It's a good idea to read library codes is often an excellent way to learn and improve your skills.

Based on your suggestion, here is the email-validator code: github.com/manishsaraan/email-vali...

Collapse
fjones profile image
FJones

Side note on using Regex to validate email addresses: stackoverflow.com/a/201378

Collapse
gaelgthomas profile image
Gaël Thomas Author • Edited

Thanks for sharing this interesting side note! 🙏

Rather than blocking the user with an error, I like the suggestion at the end:
"The specified e-mail address 'myemail@address,com' is invalid. Did you mean 'myemail@address.com'?"