4 Ways to Validate an Email with JavaScript 📮
Tags: javascript, webdev, beginners, codenewbie
Published: 2021-08-03 19:31:01

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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/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:

```regex
/^[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
```

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

```javascript
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
```

> **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](https://www.npmjs.com/package/email-validator).

Here is an example of how to use it:

```javascript
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
```

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](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email).

```html
<input type="email" id="email" name="email" placeholder="email" />
```

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

```html
<!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>
```

![Email validation using a form with an HTML5 email input](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o5vp5xjkctvm5fmwvwcp.png)

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 Twitter 🐦](https://twitter.com/gaelgthomas/)