How to Do Email Validation in JavaScript

Looking to perform front-end email validation in JavaScript?

Get started by performing a JavaScript email pattern check by entering a regex pattern into our free tool. Generate your free code to add to your website registration forms.

Try the JavaScript tool →

Enter Regex Pattern for Email Validation

Email validation determines the validity of an email address. If an email is valid, it’s real, in use, and can be used for your email marketing campaigns. If it’s invalid, it doesn’t exist or uses an invalid email format.

Validating emails is critical for keeping your email bounce rates low and maximizing your conversions. Some practical applications for JavaScript email validation include

  • Landing page registration forms
  • Newsletter signups
  • Account registration
  • eCommerce transactions

Implementing a simple Javascript email verification code on these pages can be the difference between bouncing an email and making a sale.

Why validate emails with JavaScript?

JavaScript is a widely used programming language and for great reason.

  • It’s easy to use and implement
  • It’s agile, allowing you to validate emails swiftly
  • It provides minimal strain and load to a webpage
  • It won’t cause any slowdown or negatively impact load times

Plus, it’s a prevalent language, making it easily compatible with most websites and platforms. You’ll find no shortage of guides and tutorials to assist you as you progress through the world of creating your own JavaScript email validation tool.

Understanding email format

Without something like a JavaScript email verifier to check email format, anyone can enter any characters they want on your site.

But why does that matter?

Proper email format is one of the significant distinguishers between a valid and invalid email address. An email that uses improper syntax will never be valid. And without email format validation, any visitor can enter any sequence of characters to get past your registration form.

What is the structure of a valid email address?

A valid email address will always consist of two major components:

  • The username
  • The email domain name

Both of these parts must be separated by the @ symbol. Here’s an example of a valid email address that uses the proper syntax:

john@zerobounce.net

In this example, ‘John’ is the username, and ‘zerobounce.net’ is the entire domain name. You can actually break down the domain name into two further parts: the domain name (in this example, zerobounce) and the top-level domain (.net, .com, .edu, etc.).

Be aware that some special characters are permitted for use in the username portion of an email address. The most commonly accepted special characters include numbers, periods, dashes, or underscores. However, additional characters are permitted, including:

! # $ % ^ & * ( ) - _ = + / { } ~ `

There are also special rules for certain characters. For example, periods are frequently used in email addresses (i.e., john.smith@domain.com), but the period may not begin or end the username.

To make it more complex, not all characters are accepted by all mail providers. A user may create a valid email using their email provider but have difficulty using that address to register in other locations if the site owner’s regular expression (regex) for email pattern checks does not include those particular characters.

Finally - email addresses may also have a subdomain if applicable. In these instances, you would distinguish the subdomain from the root domain by adding a period between the two (i.e., john@sales.example.com).

Importance of correct email format

“So I occasionally receive some junk data - so what?”

Any invalid email address on your list will lead to a bounce. A high email bounce rate will quickly become more than just an inconvenience.

Every company has something called a sender reputation, aka sender score. Internet service providers (ISPs) issue this sender score on a 100-point scale, with 100 being the best score possible and 0 being the lowest.

“Why does sender reputation matter?”

Your sender score is a reflection of your company/domain’s email-sending behaviors. Attributes like a high email bounce rate, poor open and click rates, or high spam complaint rate will lower your score.

A low score means that ISPs question your legitimacy and distrust your email content. Your emails will begin to go to the spam folder with frequency. Your emails may also be blocked outright.

In some cases, poor email marketing practices such as these can prompt email service providers to suspend your account.

Implementing JavaScript email verification to check email format and patterns is a necessity for keeping your company in good standing.

Implementing basic email validation using JavaScript

To get started with email validation in JavaScript, you first need a regular expression (regex) pattern.

What is a regular expression?

A regular expression is a string of text used to search for and match patterns expressed in that string.

Here’s a simple regex example that we used in our front-end email validation tool above:

^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$

Then, you can incorporate this regex for email validation into some basic JavaScript:

Note that this example uses the JavaScript regex test() method.

A JavaScript regex for email verification using the test() method identifies valid email address patterns by matching them with the characters allowed in the text string. The email format must be correct in order for the script to identify the address as valid. If the email address format breaks the rules found in the regex, it will be classified as invalid.

Alternative basic email validation methods using JavaScript

It’s vital to remember that this front-end email validation method with JavaScript is merely a pattern check.

Below are some more advanced email validation methods you should consider in addition to your JavaScript application.

Use a pre-existing JavaScript library

These libraries offer a more complex series of patterns and checks. The script allows you to detect a wide range of variables, including character type or if those characters match a predefined pattern (email, phone number, postal code, ISBN, etc.).

Examples:

contains(str, seed [, options])

check if the string contains the seed.
options is an object that defaults to { ignoreCase: false, minOccurrences: 1 }.
Options:
ignoreCase: Ignore case when doing comparison, default false.
minOccurences: Minimum number of occurrences for the seed in the string. Defaults to 1.

isFullWidth(str)

check if the string contains any full-width chars.

isLowercase(str)

check if the string is lowercase.

isNumeric(str [, options])

check if the string contains only numbers.

isWhitelisted(str, chars)

check if the string consists only of characters that appear in the whitelist chars.

isEmail(str [, options])

check if the string is an email.

These validators allow you to account for a variety of variables, such as determining the casing of the characters, checking for numbers, or allowing/disallowing based on a custom whitelist or blacklist.

You can find a full list of advanced validators and options by downloading the file from the links above or using a repository like Github.

Email validation JavaScript libraries include all of this, as well as unique error codes to spare you the legwork of creating the patterns and syntax yourself.

SMTP check or mailbox pinging

Simple Mail Transfer Protocol (SMTP) is the internet’s primary method of sending and receiving emails.

SMTP begins with the sending server sending an initial request, also known as an EHLO (Extended Hello) command. Once the sender confirms the identity of the receiving server, the emailing process continues.

We can leverage this mail server pinging to assist with email validation. By making a quick call to the domain described in an email address, we can confirm if the email domain exists or is in use.

You’ll need to connect with an external email validation service for this type of check via an API.

DNS lookups

Even with the proper syntax and an existing email domain, an email address can’t be considered validated.

A domain needs to have a Mail Exchange (MX) record in its DNS entries to receive incoming mail. Not all email addresses are created to receive messages, only to send them.

Completing a DNS lookup during your email validation process is another necessary way to ensure that the email address is usable for campaigns and won’t result in a bounce or error.

Similar to SMTP checks, you’ll need some outside help for a DNS lookup.

Best practices for JavaScript email validation

Cleaning up incoming email addresses using JavaScript isn’t just crucial for your performance; it’s a vital defense against spammy, harmful data.

When implementing a tool like this on your site or platform, be sure to use these best practices for ongoing security.

Apply JavaScript email validation to any data entry forms

For any web or platform page you have that contains a data entry form (names, emails, phone numbers, etc.), consider adding JavaScript email verification.

Even in its most basic form, the script will autodetect malformed entries and block out any data that are not appropriate for the field. Not only does this help you block invalid information, but it will provide a better user experience by giving immediate error feedback to the user. In most cases, visitors simply make mistakes during data entry and need to know what went wrong.

Take advantage of sanitizers from JavaScript libraries

When using a library like validator.js, you’ll have quick access to Sanitizers.

These provide you with a variety of ways to eliminate or replace unwanted characters from a given entry. Some examples include:

  • blacklist - Allows you to create a list of characters to block. If these characters appear in an email address entry, they’re automatically removed.
  • normalizeEmail - Automatically updates an entry to comply with the rules for different mail providers. You can account for case sensitivity and how to handle sub-address indicated by a + symbol.
  • whitelist - The opposite of a blacklist; you can create a list of allowed characters and block any that are not on your whitelist.

blacklist(input, chars)

remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need to escape some chars, e.g. blacklist(input, '\\[\\]').

normalizeEmail(email [, options])

canonicalize an email address. (This doesn't validate that the input is an email, if you want to validate the email use isEmail beforehand).

options is an object with the following keys and default values:

  • all_lowercase: true - Transforms the local part (before the @ symbol) of all email addresses to lowercase. Please note that this may violate RFC 5321, which gives providers the possibility to treat the local part of email addresses in a case sensitive way (although in practice most - yet not all - providers don't). The domain part of the email address is always lowercased, as it is case insensitive per RFC 1035.
  • gmail_lowercase: true - Gmail addresses are known to be case-insensitive, so this switch allows lowercasing them even when all_lowercase is set to false. Please note that when all_lowercase is true, Gmail addresses are lowercased regardless of the value of this setting.
  • gmail_remove_dots: true: Removes dots from the local part of the email address, as Gmail ignores them (e.g. "john.doe" and "johndoe" are considered equal).
  • gmail_remove_subaddress: true: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@gmail.com" becomes "foo@gmail.com").
  • gmail_convert_googlemaildotcom: true: Converts addresses with domain @googlemail.com to @gmail.com, as they're equivalent.
  • outlookdotcom_lowercase: true - Outlook.com addresses (including Windows Live and Hotmail) are known to be case-insensitive, so this switch allows lowercasing them even when all_lowercase is set to false. Please note that when all_lowercase is true, Outlook.com addresses are lowercased regardless of the value of this setting.
  • outlookdotcom_remove_subaddress: true: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@outlook.com" becomes "foo@outlook.com").
  • yahoo_lowercase: true - Yahoo Mail addresses are known to be case-insensitive, so this switch allows lowercasing them even when all_lowercase is set to false. Please note that when all_lowercase is true, Yahoo Mail addresses are lowercased regardless of the value of this setting.
  • yahoo_remove_subaddress: true: Normalizes addresses by removing "sub-addresses", which is the part following a "-" sign (e.g. "foo-bar@yahoo.com" becomes "foo@yahoo.com").
  • icloud_lowercase: true - iCloud addresses (including MobileMe) are known to be case-insensitive, so this switch allows lowercasing them even when all_lowercase is set to false. Please note that when all_lowercase is true, iCloud addresses are lowercased regardless of the value of this setting.
  • icloud_remove_subaddress: true: Normalizes addresses by removing "sub-addresses", which is the part following a "+" sign (e.g. "foo+bar@icloud.com" becomes "foo@icloud.com").

whitelist(input, chars)

remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will need to escape some chars, e.g. whitelist(input, '\\[\\]').

Sites without any form of character entry sanitization are vulnerable to attacks. Hackers know how to manipulate these vulnerabilities and enter strings that effectively create an unauthorized doorway into your platform. This type of vulnerability leaves both your personal information and your customers at risk.

Use clear error messages

While it’s important to block potentially harmful entries, it’s also vital to let users know why the error occurs. This information will aid visitors in correcting common mistakes so that they can provide you with their valid email addresses.

Of course - “Please enter a valid email address” is a fine start. But the more descriptive you can be, the better.

  • "Email address doesn’t contain an @ symbol"
  • "Invalid username format"
  • "Invalid email domain"

The goal is to get information from your visitors - not block it. Helping them provide the right information will help both parties get to their destination.

Test new emails even if they get past validation

Even if an email address matches your regex pattern, there’s no guarantee it’s valid. Even a misspelled entry will likely still result in an email with the appropriate syntax.

For example, John wants to enter his email address “john@gmail.com,” but instead submits “j0hn@gmail.com.” According to your JavaScript email pattern check, this is a valid email as all of these characters are permitted. But, since it does not perform a more advanced technique on its own like an SMTP check or DNS lookup, you won’t know it’s invalid.

You can send a direct email to the address. However, an invalid email address will result in a bounce. As we learned above, the higher your bounce rate, the more problems you’ll have with email deliverability.

The drawbacks of JavaScript email validation

While handy, there are several drawbacks to JavaScript email validation:

  • A regex pattern check only checks for allowed/disallowed characters. It doesn’t verify the email domain.
  • Completing SMTP checks or DNS lookups isn’t possible with JavaScript alone.
  • SMTP and DNS checks are resource-intensive - too much so for a typical server.

The first presents a significant issue as much more than improper syntax can make an email address invalid. For example, the email address “example@exampledomain4321.com” might use an accepted pattern, but it’s not an actual address that’s in use. But you have no way to confirm this without additional Simple Mail Transfer Protocol (SMTP checks) and domain verification.

Your email validation tool must be able to ping the domain to determine if the username is authentic and belongs to someone on that domain. Liken the SMTP check to dialing a number, hearing the ring, and hanging up before the connection is made. You know that the destination exists, but no actual message is sent.

Once a connection is made, you need to be able to check the DNS entries for a proper MX record. However, JavaScript alone will not be able to provide this during your email validation process. You’ll need to supplement your script with an external service capable of executing this process for you.

Finally - even if you’re able to set all of these advanced email validation techniques up in tandem with your JavaScript, the entire process is too demanding for an everyday server.

It’s not much to validate a few emails. But, once you experience a high traffic volume and need to validate in bulk, you’ll experience a noticeable performance impact, if not a server failure altogether. This may result in website outages and a poor user experience for your visitors.

The benefits of using ZeroBounce email validation over JavaScript

Versus

Has a platform dedicated to fast, 99% accurate validation
Only provides a regex pattern check
Provides a multistep validation process, including syntax, SMTP, DNS, spam trap, and additional email status checks
Can't perform advanced validation techniques like SMTP checks or DNS lookups alone
Military-grade security & privacy
Too resource-intensive for most servers
Single, batch, bulk file, and real-time email verification
Security is limited to character limitations set up by using certain validators within the script
Advanced error feedback

The limitations of using email format validation in JavaScript are why many turn to a dedicated email validation service like ZeroBounce.

In addition to a comprehensive spelling, pattern, and syntax check, the email verifier offers a more comprehensive, accurate check, along with these additional benefits:

Real-time email validation

You can clean email addresses in real time with Zerobounce email validation.

What does that mean?

The email validation tool features an API that you can quickly add to any website, landing page, or one of your favorite platforms. Plus - you can use the email validation API in JavaScript since that’s likely your preferred programming language. If that’s not your speed, other languages like PHP, Python, or C++ are available.

Once the email verification tool is on your page, anytime someone enters their email address into your registration form, it undergoes validation. That check includes the email pattern check, the SMTP check, and a series of additional checks to ensure validity.

If the email address is valid - it goes to your list. If it’s invalid, it’s blocked, and the user needs to enter a new one until it’s valid.

Real-time email validation saves you the hassle of manually checking every email address or constantly uploading new email lists for cleaning.

Sophisticated email status detection

While the JavaScript regex for email merely checks for syntax, ZeroBounce email validation provides a series of additional checks. The entire process includes the following:

  • Pattern/syntax check - Spot typos or invalid characters
  • DNS record check - Does the domain have the appropriate MX or A-type record?
  • Spam trap check - Does the address contain signatures associated with known traps?
  • SMTP check - Ping the email domain
  • Additional status check - Is this a catch-all? A disposable domain? An abuse email? On a global suppression list?
  • "Unknown" recheck - Any email addresses that are initially “unknown” are rechecked, a great way to bypass spam filters like greylisting

All of these additional checks provide far more substantial information about the email address in question when compared to a simple JavaScript email pattern check.

You’ll know for certainty not just if the email is valid but if it is potentially some other high-risk email type that you’re better off leaving off of your contact list.

Advanced error feedback:

To supplement those enhanced email validation checks, ZeroBounce provides a quality, descriptive reason for any errors encountered. You’ll not only know if the email address failed the syntax check but alternative issues, including

  • The mailbox is full.
  • The mailbox doesn’t accept incoming emails.
  • No DNS entries are present.
  • There’s an unroutable IP address.
  • The mail server didn’t respond.
  • An antispam system is present.

This advanced email validation provides over 30 status and sub-status codes for definitive feedback. Basic JavaScript email verification can’t provide the level of knowledge required to make more advanced email marketing decisions or to protect your sender reputation.

99% accuracy guarantee with fewer "unknowns"

This advanced email validation method is 99% accurate with a purchase guarantee. The precision and feedback offered allow ZeroBounce to provide up to 100% fewer unknowns compared to many competitors when verifying certain email domains.

What is an "unknown?"

An “unknown” result is what you get any time your email verification method can’t validate an address or any address associated with a domain. Essentially, the tool doesn’t have and will never have the means to verify that address.

ZeroBounce’s multistep validation process ensures that you know everything there is to know about your email list with effectively 0 unknown results.

Comprehensive data security

Keeping your company’s data is always a necessity. However, front-end email validation with JavaScript provides no advanced security benefits outside of general pattern detection that blocks unwanted characters.

ZeroBounce’s email validation features military-grade security and privacy, built by some of the most talented web security experts around the world.

Real-time syntax, SMTP, and DNS checks

Whether you’re using the bulk file uploader or the real-time email verifier API, your data will undergo the same syntax and data entry checks required to eliminate outdated or harmful data from any list. These features include the ability to autodetect typos or misspellings and autocorrect them to create a valid address.

Any malformed, irrecoverable addresses will not be processed, and you’ll receive a notification explaining that the data is unusable in its current state, along with possible explanations.

When using ZeroBounce on your website or platform, it will also autodetect other types of valid but risky emails like disposable domains, toxic domains, catch-alls, do-not-mail addresses, etc. The domain and DNS check happens in real time, giving you greater control over which emails are considered valid and may enter your database.

Global privacy compliance for all industries

Many industries have very rigid privacy standards that greatly limit what type of email validation method you can use.

ZeroBounce accounts for this by actively maintaining compliance and being SOC 2 Type 2 and ISO-27001 certified. The platform is also compliant with GDPR, HIPAA, CCPA, and PCI-DSS.

In addition, none of your processed data is ever stored on any ZeroBounce servers. All email validation occurs in real time, and your results are delivered in a military-grade encrypted file that only you can access with your unique password.

Platform cybersecurity

Finally, to protect your data from hackers, spammers, and spoofers, ZeroBounce regularly performs penetration testing and risk management with the help of partners like Hacker1 - a community-based group of white-hat hackers that assist us in discovering potential vulnerabilities to keep up with the newest and latest attack methods constantly.

You also never need to worry about the limitations of strain, as ZeroBounce’s platform is dedicated to providing 24/7, reliable email validation. It’s all backed by unmetered DDOS and WAF protection courtesy of Cloudflare Enterprise.

Learn more about ZeroBounce security and compliance →

How to use ZeroBounce email validation

There are three ways to handle your email verification with ZeroBounce:

Method 1 - Bulk file upload

The simplest method is to upload your email list file to the email validation platform. You can use a CSV, XLS, XLSX, or TXT file to begin the cleaning process.

Alternatively, you can integrate your CRM or email provider with ZeroBounce to import your list directly.

See the complete list of integrations →

After uploading your list, the validation process begins. ZeroBounce will automatically notify you when the process is complete so that you can download your results.

You’ll find your emails stored in an encrypted zip file. Inside, there will be multiple subfolders that filter your validation results by status (valid, invalid, catch-all, do_not_mail, etc.).

Method 2 - Individual or batch validation

If you need a single email pattern check or want to investigate a smaller list, you can enter addresses directly into the validator.

Instead of downloading your results in a file, they’ll appear immediately next to the emails you entered on your dashboard.

Real-time API email validation

If you’re fond of JavaScript (that’s why you’re here, right?), you can use it to set up the ZeroBounce email validation API.

ZeroBounce supports JavaScript email verification when using the API endpoint. If you prefer to use another language, 15 are currently supported, including Ruby, Python, C++, PHP, iOS, Android, and more.

Similar to the JavaScript email pattern check, you can add the ZeroBounce API code to your website or platform of choice. For example, adding the API to a website registration form allows you to benefit from real-time email verification of any entered email address.

The only difference is that you’ll receive all of the aforementioned validation checks in addition to a standard email pattern check. If the address is invalid or high-risk, it gets blocked automatically.

You can also use the real-time email validation API to submit manual rests, either individual or bulk file uploads, and receive your results accordingly.

For starters, you can try out the ZeroBounce JavaScript email validation API using a repository like POSTMAN with the following JSON file:

You can also test it for free without expending credits by using the email address examples listed in our Sandbox Mode documentation.

Then, you can start leveraging the various endpoints for the following features:

Single email validation using JavaScript

API endpoint URL (EU): https://api.zerobounce.net/v2/validate

API endpoint URL (US): https://api-us.zerobounce.net/v2/validate

URL Parameters

Parameter

Description

email

The email address you want to validate

ip_address

The IP address the email signed up from

api_key

Your ZeroBounce API key

Batch email validation

API endpoint URL: https://bulkapi.zerobounce.net/v2/validatebatch

URL Parameters

Parameter

Description

api_key

Your API key

email_batch

[Array of Objects], Format:{"email_address": "valid@example.com","ip_address": "1.1.1.1"}

Bulk email list file upload

API endpoint URL: https://bulkapi.zerobounce.net/v2/sendfile

URL Parameters

Parameter

Description

file

csv or txt file. Byte array contents for the submitted file. The content's header is type of "text/csv".

api_key

Your ZeroBounce API key

return_URL

The URL will be used to call back when the validation is completed. (Optional)

email_address_column

The column index of the email address in the file. Index starts from 1. (Required)

first_name_column

The column index of the first name column. (Optional)

last_name_column

The column index of the last name column. (Optional)

gender_column

The column index of the gender column. (Optional)

ip_address_column

The IP Address the email signed up from. (Optional)

has_header_row

If the first row from the submitted file is a header row. true or false (Optional)

remove_duplicate

If you want the system to remove duplicate emails (true or false, default is true). Please note that if we remove more than 50% of the lines because of duplicates (parameter is true), system will return a 400 bad request error as a safety net to let you know that more than 50% of the file has been modified.

You can find a full list of all ZeroBounce email verification API features by reviewing the full documentation. There are also JavaScript SDK wrappers available for use.

Email verification you can count on

No matter if you use JavaScript email validation or a more advanced email verification software, remember to verify.

Remember, failing to clean your emails results in

If your emails aren’t reaching real customers or finding the inbox, then your email marketing isn’t worth the effort.

Be sure to use our free JavaScript email validation tool above to create a basic email pattern check that you can use to block invalid emails. But, if you want more advanced validation to safeguard your company’s reputation, join ZeroBounce for free today.