5

4 Ways to Validate an Email with JavaScript 📮

 3 years ago
source link: https://dev.to/gaelgthomas/how-to-validate-an-email-with-javascript-25k3
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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 modeExit 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('[email protected]')) // true
console.log(isEmailValid('[email protected]')) // true
console.log(isEmailValid('[email protected]')) // true
console.log(isEmailValid('[email protected]')) // true
console.log(isEmailValid('[email protected]')) // false
console.log(isEmailValid('[email protected]')) // false
console.log(isEmailValid('@herewecode.io')) // false
console.log(isEmailValid('helloitsmeherewecode.io')) // false
console.log(isEmailValid('helloitsme@herewecode')) // false
console.log(isEmailValid('[email protected]')) // false
Enter fullscreen modeExit 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('[email protected]')) // true
console.log(validator.validate('[email protected]')) // true
console.log(validator.validate('[email protected]')) // true
console.log(validator.validate('[email protected]')) // true
console.log(validator.validate('[email protected]')) // false
console.log(validator.validate('[email protected]')) // 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('[email protected]')) // false
Enter fullscreen modeExit 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 modeExit 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 modeExit 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'm starting to tweet more consistently! If you want to get more tips and resources about web programming -> Find me on my Twitter 🐦


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK