How To Validate An Email in Javascript

How To Validate An Email in Javascript

Email is the most open and utilized form of communication on the internet. Unlike most social media platforms, it is an open protocol that has been battle tested by the public for over 50 years. That said, you don’t stay backward compatible for that long and not develop some pains around tooling.

In this article, we’ll focus on one aspect of the tooling that still requires you to construct yourself: email validation. Email validation is critical in the never-ending fight against spam. You can also use it to determine if a user mistyped a valid email address. Or if someone is using a temporary email address service. We’ll walk through some of your options available as well as options involving external services.

Validate Emails With Just JavaScript (Regex)

No alt text provided for this image

The simplest way to validate an email address is with regular expressions. You can embed regular expressions into your own scripts or integrate them into an existing application.

Here's an example of how you might do?it, using the standard regex that's built into the HTML5 protocol:

var regex =?/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+Itacate Foods-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/


function validateEmail(email)?{
  if (regex.test(email))?{
    console.log("Valid Email Address");
  } 
  else?{
    console.error("Invalid Email?Address!");
  }
};        

The check itself has limitations, however. On the client side, it's great as a quick sanity check but you can't trust the input. A user can always edit the script on their machine, so you'll still need a server-side check.

It's also difficult for testers or QA teams to use this snippet if they don't already know javascript. Finally, your backend still has to do validation as a final check.

Pros and Cons of the Regex Approach

Validating inside your application has its advantages but also some disadvantages. The advantages are a small number of dependencies and the ability to tweak your validation filters to your preferences.

The disadvantages are:

  1. Maintenance costs that come along with all code you write
  2. The need to test the custom filters you add (ie not allowing any gmail.com accounts)
  3. You will need to write any extra validation by hand (ie domain aliases for a given email domain)

Thankfully there's a host of services to address these disadvantages.

Validate Emails With A Third-Party Service?

You can validate emails through a variety of external services. For example, there are plugins to MailChimp that offer email validation. SendHub also provides a validation service for your?customers.

We recommend you use our service here at Mailsac for your validation needs. You can validate your emails via an API or directly through our website. We also provide a service that lets you validate an email address via our website or REST API.

No alt text provided for this image

Additionally, we have an email capture service. This service traps all emails sent through our capture service ensuring it never routes to a real inbox. Capturing emails can be invaluable during testing after email validation. For example, you can use it to ensure the email content sent is identical to the content received.

No alt text provided for this image

We know it can be a time-consuming process, but email validation is worth it if you want to avoid sending unwanted emails that can cost you (CPU) time and money. Validating emails is a step in the right direction in protecting your business and customers' data.

We'll wrap this article up with a quick guide on validating emails with Mailsac.

Guide To Validating Emails with Mailsac

First, we can start by signing up for an account at mailsac.com

No alt text provided for this image

After signing up, you have two options:

  1. Validate emails manually via the email validation link in the dashboard or
  2. Generate an API key from the dashboard

No alt text provided for this image

Validating Via Website

To validate via the website, just supply an email and hit enter:

No alt text provided for this image

Validating Via The API

Since our API is REST-based you can use any client or framework that speaks to the HTTP endpoint.

For example, using standard curl:

curl -H 'Mailsac-Key: YOUR_API_KEY_HERE' https://mailsac.com/api/validations/addresses/[email protected],

# Output from curl
{
  "email": "[email protected]",
  "domain": "mailsac.com",
  "isValidFormat": true,
  "local": "jimmy",
  "isDisposable": true,
  "disposableDomains": [
    "ledoktre.com",
    "mailsac.com",
    "totalvista.com",
    "slothmail.net"
  ],
  "aliases": [
    "ledoktre.com",
    "mailsac.com",
    "totalvista.com",
    "52.41.136.113",
    "slothmail.net",
    "aiwa.fm",
    "tztmax.com",
    "cs.msdc.co",
    "zeie.xyz",
    "yinpinpin.club",
    "jadeant.top",
    "dylans.email",
    "msdc.co"
  ]
}        

Using Node.js with superagent:

const superagent = require('superagent'

superagent
  .get('https://mailsac.com/api/validations/addresses/[email protected]')
  .set('Mailsac-Key', 'YOUR_API_KEY_HERE')
  .then((validation) => {
      console.log(validation.body)
  })
  .catch(err => {
      console.log(err.message)
  })
/*
{
  email: '[email protected]',
  domain: 'mailsac.com',
  isValidFormat: true,
  local: 'jimmy',
  isDisposable: true,
  disposableDomains: [ 'ledoktre.com', 'mailsac.com', 'totalvista.com', 'slothmail.net' ],
  aliases: [
    'ledoktre.com',   'mailsac.com',
    'totalvista.com', '52.41.136.113',
    'slothmail.net',  'aiwa.fm',
    'tztmax.com',     'cs.msdc.co',
    'zeie.xyz',       'yinpinpin.club',
    'jadeant.top',    'dylans.email',
    'msdc.co'
  ]
}
*/
)        

Additional options can be found in the API documentation.

Conclusion

To wrap up, we've touched on a couple of different ways to validate email addresses. We also showcased a couple of external services that handle email validation and included a guide to using our own.

We hope the article was useful to you. If you want to provide feedback we have a forum where we discuss a myriad of issues or you can send us a message here on LinkedIn.

要查看或添加评论,请登录

Mailsac的更多文章