How To Create A Custom Email Validation Error Message

Last Updated Jun 06, 2022
Shyam Purkayastha

Shyam is the Founder of Radiostud.io, a content-lead innovation studio, focusing on showcasing use cases of emerging technologies. He's an entrepreneur, a technology evangelist, author, and mentor with a deep passion for nurturing ideas and building things around emerging and futuristic trends in Computing, Information Technology, and Telecommunications.

Table of Contents:

Despite being the most convenient form of communication over the web, emails attract a lot of notoriety. Dealing with spam and fake e-mail ids is the bane of any online user. The biggest question is: how does one validate email addresses? From an online marketing perspective, it is all about generating email validation error messages to improve the conversion rate of a marketing campaign. 

This post covers the best practices for handling e-mail validation along with developer techniques for building e-mail validation code on the server side. You are expected to have an intermediate level of familiarity with Node.js to understand the code snippets and examples presented here.  

Don't reinvent the wheel.
Abstract's APIs are production-ready now.

Abstract's suite of API's are built to save you time. You don't need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that's actually valuable for your app or business, and we'll handle the rest.

Get started for free

What is a Validation Error Message?

Online marketers rely on e-mail lists to target prospective customers. Automating the subscription opt-in process to weed out any invalid email address is an effective way to ensure the sanity of the list. But many times, checking for a valid email is a binary, yes or no decision, with a generic error message, such as “Invalid Email Address” displayed on the user interface.

What you need is a mechanism to validate email addresses objectively. This entails capturing the email address from the input field and checking it for the server configuration, SMTP status, roles, and disposability of an email address to classify it under various categories that define the probability of reaching the intended recipient.

Thankfully, all of this is possible with just an API call. The Abstract E mail Validation and Verification API gives you a comprehensive report so that you can validate various aspects of an email address to generate custom error messages for things such as:

  • Basic formatting: Checking for invalid email address format and recommending corrections for typos.
  • Non-personal categorization: Checking for role-based emails, such as sales@example.com, or catch-all email ids like hello@example.com not associated with a person.
  • Mail Server Configuration Validation: Checking for the SMTP server and MX record status to ensure that the emails are not handled by span services.
  • Quality Score: A quality score between 0.01 to 0.99, reflecting Abstract's confidence in the quality and deliverability of the submitted e-mail.

Error Message Best Practices

Error messages are the first source of information about something going amiss with an email address. Therefore, it is important to build a mechanism such that the messages are well articulated to aid the specific use case.

Here are some essential guidelines to write error messages that are instantly decipherable:

  1. Clear Text: For understanding technical jargon, clarity triumphs over complexity. A clear error message is easier to read than trying to figure out an error message loaded with complex technical terms, such as “SMTP Error” or “MX Record not found”.   
  2. Helpful Information: For a better user experience, it is good to provide helpful information in the error message to build empathy with the user. As an example, providing a recommendation for a typo in the email address would go a long way to build empathy, instead of showing a blunt “Email Address Not Found” error message.  
  3. Situation Specific Content: The error message should be customized to the error situation. For example, in case of a formatting issue, it is better to show that explicitly, rather than displaying something like “Invalid Email”.

Creating Custom Error Messages

Using Abstract’s E mail Validation and Verification API, you can plug in your e-mail validation logic with custom error messages. 

First, let’s test the API to get a sense of what it offers. Signup for a free account on Abstract and head over to the API dashboard.

Perform a live test of the API.

You should get a response from the API, containing several fields that validate the email address for various checks.

Considering a genuine email address, the complete API response in JSON formal looks somewhat like this.


{
    "email": "some@validemail.com",
    "autocorrect": "",
    "deliverability": "DELIVERABLE",
    "quality_score": "0.99",
    "is_valid_format": {
        "value": true,
        "text": "TRUE"
    },
    "is_free_email": {
        "value": false,
        "text": "FALSE"
    },
    "is_disposable_email": {
        "value": false,
        "text": "FALSE"
    },
    "is_role_email": {
        "value": false,
        "text": "FALSE"
    },
    "is_catchall_email": {
        "value": true,
        "text": "TRUE"
    },
    "is_mx_found": {
        "value": true,
        "text": "TRUE"
    },
    "is_smtp_valid": {
        "value": true,
        "text": "TRUE"
    }
}

You can see that the API checks the email address at syntax, semantic, and systemic levels. For instance, the field “is_valid_format” checks for the syntax of the email address. “is_role_email” checks for the semantic meaning of the email id. Similarly, “is_mx_found” checks for a valid MX record on the domain that hosts the email.

Keeping the best practices in mind, it is possible to build a custom validation logic based on a layered approach that performs the various syntax, semantics, and the systemic level validations of an email address.

Syntax Level

Syntax level checking ensures that the email address is formatted correctly, with the mandatory ‘@’ and ‘.’ characters and some minimum number of characters.

You can call the Abstract Email Validation and Verification API with the Axios HTTP client for Node.js and check for the format.


let response =  await axios.get('https://emailvalidation.abstractapi.com/v1/?api_key=' + <YOUR_ABSTRACT_API_KEY> + '&email=mail@example.com’)
    

if(!response.data.is_valid_format.value){
  throw new Error("Invalid Email Format")
}

Semantic Level

Semantic level checks decipher the email address to find out associations with a persona or type of e-mail service.

For example, if a website is collecting email addresses of readers who want to read a newsletter, then the website owner would want to validate the user input to ensure that the emails belong to an actual human, instead of some role or catchall e mail id. Also, the email addresses should belong to a well-known domain with good domain authority, instead of some temporary email service.

The API response returned by Abstract Email Validation and Verification API has specific flags to identify these categories.


let response =  await axios.get('https://emailvalidation.abstractapi.com/v1/?api_key=' + <YOUR_ABSTRACT_API_KEY> + '&email=mail@example.com’)

if (response.data.is_free_email.value || response.data.is_disposable_email.value){
    throw new Error("Free/Disposable Email")
} else if (response.data.is_role_email.value || response.data.is_catchall_email.value){
    throw new Error("Generic (Role / Catchall) Email")
}

Systemic Level

Systemic level checks ensure that the e-mail server configuration records are valid. These are specific to the MX record and SMTP domain configuration settings.


let response =  await axios.get('https://emailvalidation.abstractapi.com/v1/?api_key=' + <ABSTRACT_API_KEY> + '&email=mail@xample.com’)

if (!response.data.is_mx_found.value){
    throw new Error("Invalid Email Record")
} else if (!response.data.is_smtp_valid.value){
    throw new Error("Invalid Email Id or Unknown Mail Server")
}

Creating Dynamic Error Messages

While it is good to have specific error messages for email addresses, it is possible to enhance the user experience by customizing the error message further.

For example, let’s assume your website has a subscription form with an input field that accepts email addresses from visitors who opt-in for your newsletter. On the server side, you can incorporate the Abstract Email Validation and Verification API. With a Node.js / Express.js-based stack, it is easy to add the e-mail validation using the express-validator library.

Here is how you can define an API endpoint ‘GET  /subscribe’ that performs a custom validation of e-mail to return specific error messages based on the response from Abstract Email Validation and Verification API.


const express = require('express')
const bodyParser = require('body-parser');
const axios = require('axios')
const app = express()
const { body, validationResult } = require('express-validator');
const port = 3000

const ABSTRACT_API_KEY = "<YOUR_ABSTRACT_API_KEY>"

//app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

async function validationEmail(val, {req}){

  let response =  await axios.get('https://emailvalidation.abstractapi.com/v1/?api_key=' + ABSTRACT_API_KEY + '&email=' + val)
    
  console.log(response.data)  

  if(!response.data.is_valid_format.value){
    throw new Error("Invalid Email Format")
  } else if (response.data.is_free_email.value || response.data.is_disposable_email.value){
    throw new Error("Free/Disposable Email")
  } else if (response.data.is_role_email.value || response.data.is_catchall_email.value){
    throw new Error("Generic (Role / Catchall) Email")
  } else if (!response.data.is_mx_found.value){
    throw new Error("Invalid Email Record")
  } else if (!response.data.is_smtp_valid.value){
    throw new Error("Invalid Email Id or Unknown Mail Server")
  }

  return true
}




app.post('/subscribe',
         body('email').custom(validationEmail),  
         async (req, res) => {

          const errors = await validationResult(req);

          console.log(errors);
          
          if (!errors.isEmpty()) {
            return res.status(400).json({ status: "fail", errors: errors.array() });
          }
         
          console.log("Adding New Subscriber " + req.body.email + " to Database")  
          return res.status(200).json({ status: "success", errors: "[]" });
         
})

Make a new Node.js project and install express, Axios, and express-validator libraries using the npm tool. Also, save the above code as the source file named app.js, and replace the placeholder <YOUR_ABSTRACT_API_KEY> with your Abstract API key.

Upon running this code, you can test the API with several invalid email addresses, to get the desired error message with the HTTP 400 error code. In the case of a valid email address, it returns a 200 OK response.

To make the error messages more dynamic, you can further analyze the Abstract Email Validation and Verification API response against an email address query to capture:

  1. Quality score: This provides an indicative probability of spam email addresses. Your error message can contain additional information that translates this quality score to a range of quality attributes for email addresses.
  2. Auto-Correction: This is a recommendation for the possible valid e-mail ids, in case the queried email address is invalid.
  3. Deliverability: This parameter checks whether the emails sent to the queried email address are deliverable or not. This can provide an additional warning to show if emails are not deliverable.

Validation Error Message FAQs

What Is a Validation Error Message?

A validation error message provides information about the validity of an email address. It can contain syntax, semantics, and system-related error messages to find out whether an email address is valid. With the help of Abstract Email Validation and Verification API, it is possible to perform various validation checks on an email address.

What does Email Validation Mean? 

Email validation is the process of validating the various aspects of an email address, from format to server and DNS-related configuration, and more. The Abstract Email Validation and Verification API can validate various aspects of an email address, such as its format, nature of the email service (free or disposable), type of email id (personal or role-based or catch-all), and more.

How Do You Add A Validation Error Message?

You can add validation error messages on the server side while accepting the email addresses as part of an API request. If using a Node.js/Express.js stack, you can wrap the Abstract Email Validation and Verification API as part of the express-validator library to build custom error messages in API responses.

Improve your delivery rate with the industry-leading email verification API from Abstract.

Get started for free
Improve your delivery rate with the industry-leading email verification API from Abstract.
Get started