Guides
Last Updated Jan 11, 2024

How To Validate Multiple Email Addresses with JQuery and PHP

Shyam Purkayastha

Table of Contents:

Get your free
API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required
Get your free
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
START FOR FREE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required

There are many email address-centric apps out there, such as mailing list management and customer data management software. Some of the workflows in these applications involve handling multiple email addresses at the same time. So there needs to be an efficient way to validate email addresses.

In this article, we will address this problem using JQuery and PHP to demonstrate how you can handle multiple email address validation with minimum effort.

Key Takeaways

  • The article focuses on efficiently validating multiple email addresses using JQuery and PHP, a necessity in many email-centric applications like mailing lists and customer data management.
  • JQuery, while primarily a JavaScript-based library for dynamic web applications, can be augmented with plugins for specific tasks like email validation.
  • PHP serves as a robust backend solution, working in tandem with JQuery to ensure comprehensive email validation, including checks for valid domains, MX records, and SMTP hosting.
  • The use of a JQuery plugin for multiple email validation is demonstrated, showcasing its integration into a web application.
  • The article also introduces the Abstract Email Validation API as an advanced solution for validating email addresses beyond basic format checks, emphasizing its ability to verify domain legitimacy and SMTP validity.
  • Practical considerations such as responsiveness, input data validation, handling typos, and regulatory compliance are also discussed.

Let’s send your first free
API
Email Verification API
call
See why the best developers build on Abstract
Get your free api

Why JQuery and PHP for Email Validation?

JQuery is a JavaScript-based library for building web applications. At the core, it offers a simpler interface for performing dynamic operations on the DOM. Also, it provides a browser-agnostic SDK for some of the complex operations such as AJAX, UI rendering, and animations.

If you are building a web application based on Bootstrap from scratch, JQuery is a good choice. Together with PHP, it forms an excellent combination of a stable web development stack. However, JQuery is suited for traditional, form-oriented applications meant for data entry and analysis. If you are building a highly interactive, single-page web application, there are modern web frameworks like Angular, and React which surpass JQuery’s capabilities by leaps and bounds.

Nevertheless, JQuery has been around since the early days of Web 2.0 and therefore has a mature ecosystem of third-party plugins. JQuery itself does not provide any facilities for validating emails and instead relies on JavaScript. However, many plugins offer an easy-to-use UI interface for submitting multiple emails. Since our focus in this article is on multiple email validation, let’s build a demo web application using a JQuery plugin and PHP to showcase this functionality.  But before that, let’s take a look at some practical use cases of multiple email address validation.

Practical Use Cases of Multiple Email Address Validation

Here are some of the most relevant use case scenarios for bulk email address validation:

1. Marketing: Marketing teams handle a lot of customer contact data, and email is the most effective outreach tool in this age of the Internet. Some of the marketing activities that involve handling multiple email addresses include:

a. Personalised campaigns targeted at a few specific persons.

b. Mailing list/subscription list onboarding and management for a group of users.

2. Customer Relationship: CRM teams also deal with a lot of email correspondence, and entering multiple emails is a regular activity in some of their workflows such as:

a. Lead/Prospect entry with multiple contact persons from the client organization.

b. Transactions and notification management associated with users with multiple email addresses.

c. Customer data migration from one system to another.

3. Government and Public Sector: Government portals collect emails for citizen communication, wherein multiple email addresses are often required for:

a. Family member registration with multiple email addresses belonging to each family member.

b. Bulk validation of multiple email addresses to ensure accurate contact information for a subset of the population.

How to Validate Multiple Email Addresses in JQuery

This demo application relies on a web-based interface for accepting multiple email addresses from a UI, which is controlled by a JQuery plugin. Like any typical web application, there are two components involved here, a frontend and a backend. The frontend is based on JavaScript/JQuery and the backend is based on PHP.

Follow the below tutorial steps to build and test this application for multiple email validation use cases.

Demo Project Setup

Before getting into the code-level details of this app, you must set your development environment with the following prerequisites:

  1. A PHP runtime environment, with at least version 8.0 or above.
  2. A project directory for the demo application with the following subdirectory structure.

This project has the following source files (currently left blank):

a. validateEmail.js: This will contain the JQuery code for rendering the UI for multiple email addresses.

b.index.html: This is the overall HTML file that represents the front end of the application.

c. index.php: This will contain the backend PHP code for this application.

  1. A JQuery plugin: Download this JQuery plugin for multiple email validation. Unzip the downloaded plugin ZIP file and extract it within the plugin subdirectory.

Note: The choice of this JQuery validation plugin is purely arbitrary, and based on the supported functionality and testing. This is not an official plugin endorsed by JQuery.  

The final directory structure, after extracting the plugin should look like this.

Let’s add some code to the source files, step by step, and build this app.

Step 1: Add the HTML Code

Open the index.html file and add the following code:


<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

    <title>JQuery Multiple Email Validation</title>

    <!-- Add Bootstrap CSS -->

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

    <!-- Add multi-email plugin CSS -->

    <link rel="stylesheet" href="plugin/multiple-email-input/css/jquery.multi-emails.css"></link>

    <!-- Add JQuery -->

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

    <!-- Add JQuery Multi-email Input Plugin -->

    <script src="plugin/multiple-email-input/js/jquery.multi-emails.js"></script>

</head>

<body>

<div class="row">

        <div class="container mt-5 col-sm-4">

            <h4>Multiple Email Validation</h4>

            <p>Type comma(,) to add next email</p>

            <form class="form-container" id="emailForm">

                <!-- Multi-email input field -->

                <div class="email-input">

                    <input type="text" name="emails" id="emails" class="form-control"

                        placeholder="Enter email addresses">

                </div>

                <button type="submit" class="btn btn-primary mt-2">Validate Emails</button>

            </form>

            <div id="result" class="mt-3"></div>

        </div>

        <div class="col-sm-6"></div>

    </div>




    <!-- Bootstrap JS for styling -->

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

    <!-- Custom JavaScript file -->

    <script src="js/validateEmail.js"></script>

</body>

</html> 

This is a basic HTML code based on the default Bootstrap theme and JQuery. It has a single <form> element with one field for accepting the email address. There is also an <div> element with the id “result”. These two elements will be attached to JQuery for dynamic manipulation later.

Save this file. To test it, open a terminal window, change to the project directory path, and run the PHP development server as follows:


php -S localhost:8000 


Open a browser tab and point to the URL http://localhost:8000/index.html.

This will render the HTML page with the form.

At this point, it is just a static page, so let’s add some interactivity to it in the next step.

Step 2: Activate JQuery Multiple Email Validation Plugin

Open the file validateEmail.js and add the following code:


$(document).ready(function(){

    $("#emails").multiEmails();

});

This code attaches the JQuery plugin to the HTML form input text element with id “emails”. Save the file and reload the HTML page on the browser.

Now you can see the plugin in action, as it can accept multiple email addresses and list them below the input field.

As you have witnessed, this plugin is capable of performing the basic email address validation check and it also flags the invalid email address. Therefore, this plugin can perform the basic multi-email address validation by default. This feature takes care of frontend form validation of email addresses without writing additional JavaScript code.

But to complete the loop of the validation functionality, you need to submit the email addresses to the server. Let’s add the backend PHP logic for that.

Step 3: Add PHP Code for Backend Validation

Open the file index.php and add the following code:


<?php


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Retrieve the JSON-encoded array from the 'emails' field

    $encodedEmails = $_POST['emails'];


    // Decode the JSON array

    $emailsArray = json_decode($encodedEmails);




    if ($emailsArray !== null && is_array($emailsArray)) {

        // Convert any objects to strings

        $emailsArray = array_map('strval', $emailsArray);


        $validEmails = [];


        foreach ($emailsArray as $email) {

            $trimmedEmail = trim($email);

            // Validate using a custom regex pattern for Gmail or Yahoo domains

            $pattern = '/@(gmail\.com|yahoo\.com)$/i';


            if (filter_var($trimmedEmail, FILTER_VALIDATE_EMAIL) && preg_match($pattern, $trimmedEmail)) {

                $validEmails[] = $trimmedEmail;

            }

        }


        echo 'Valid Emails: ' . implode(', ', $validEmails);


    } else {

        echo 'Invalid JSON format or empty array';

    }

} else {

    echo 'Invalid Request';

}

?>


This is a simple PHP code for handling an AJAX POST request from the frontend. This code accepts the email addresses from the POST parameters, parses them, and validates them individually. At the end, a list of valid email addresses is returned.

Since the basic email address validation is already performed at the frontend, this PHP code performs a custom validation to make sure that the email addresses belong to select domains. A regular expression pattern is used here to filter out any email address that does not belong to “gmail.com” or “yahoo.com” domains.

Before you can test this code, you have to add the submit functionality at the frontend so that the plugin can make an AJAX call to send the list of emails to the backend.

Step 4: Add Form Submission Code

Open the file validateEmail.js again and append the following code after the existing code you added in step 2.


$('#emailForm').submit(function(e){

        e.preventDefault();

        // Get the array of emails directly

        var emailsArray = $("#emails").val();

        emailsArray = JSON.parse(emailsArray);


        $.ajax({

            type: 'POST',

            url: 'index.php',

            data: { emails: JSON.stringify(emailsArray) },

            success: function(response){

                $('#result').html(response);

            },

            error: function(error){

                console.log(error);

            }

        });

    });

This code attaches a submit event to the submit button. Within this event, an AJAX call is performed to trigger the index.php, passing a comma-separated list of all email addresses.

Save the file. Refresh the browser tab and you can test multi-email address validation.

Now, the entire loop between the frontend and the backend is complete. The JQuery plugin is validating the basic email address format, while the backend PHP is ensuring that only the email addresses with “gmail.com” and “yahoo.com” domains are accepted.

A Better Solution: Abstract API

The regular expression-based email validation works fine for limited use within a specific domain or enterprise intranet environment.  But in case you are building an online application accessible from anywhere in the world, you cannot limit the users to specific email domains only.

This scenario calls for additional checks on the email address to verify the authenticity of the address and its domain, such as a valid DNS MX record, and the presence of an SMTP server to route the emails. These checks cannot be performed locally within the code.

Fortunately, there is an easy way out. Using the Abstract Email Validation and Verification API, you can get a detailed report on the legitimacy of any email address, including its format, and the presence of valid MX record and SMTP endpoint.

Here is another modified version of index.php that uses the Abstract API endpoint:


<?php


function validation_with_abstract($email)

{

        $url = "https://emailvalidation.abstractapi.com/v1/?api_key=" . "<YOUR_ABSTRACTAPI_KEY>" . "&email=" . $email;

        $curl = curl_init();

        curl_setopt_array($curl, array(

           CURLOPT_URL => $url,

           CURLOPT_RETURNTRANSFER => true,

           CURLOPT_ENCODING => '',

           CURLOPT_MAXREDIRS => 10,

           CURLOPT_TIMEOUT => 0,

           CURLOPT_FOLLOWLOCATION => true,

           CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

           CURLOPT_CUSTOMREQUEST => 'GET',

           CURLOPT_HTTPHEADER => array(

               'Content-Type: application/json',

               'Accept: application/json'

           ),

        ));

        $response = curl_exec($curl);

        curl_close($curl);

        $result = json_decode($response, true);


        return $result['is_valid_format']['value'] && $result['is_mx_found']['value'] && $result['is_smtp_valid']['value'];


}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Retrieve the JSON-encoded array from the 'emails' field

    $encodedEmails = $_POST['emails'];


    // Decode the JSON array

    $emailsArray = json_decode($encodedEmails);


    if ($emailsArray !== null && is_array($emailsArray)) {

        // Convert any objects to strings

        $emailsArray = array_map('strval', $emailsArray);


        $validEmails = [];


        foreach ($emailsArray as $email) {

            $trimmedEmail = trim($email);

           

            $isValid = validation_with_abstract($trimmedEmail);


            if ($isValid) {

                $validEmails[] = $trimmedEmail;

            }

        }


        echo 'Valid Emails: ' . implode(', ', $validEmails);


    } else {

        echo 'Invalid JSON format or empty array';

    }

} else {

    echo 'Invalid Request';

}

?>

This code relies on the PHP cURL library to call the Abstract API and get a validation result for all the email addresses submitted via the AJAX request. It specifically checks for the email address format, MX, and SMTP validity of every email address. To know more about the various validation result parameters returned by the API, you can check the API documentation.

Before saving this file, you have to replace the placeholder <YOUR_ABSTRACTAPI_KEY> with an API key. You can sign up for an account of Abstract API and get your API key to make free API calls to this API. Post login, you can check the API key allotted to you within the API dashboard.

Now it's time for the final test of multiple email validation using JQuery and PHP with advanced validation powered by Abstract API.  

As you can see, this demo application accepts only legitimate email addresses and rejects junk and spurious email addresses, even if they have the correct format. If you want to filter email based on specific domains, then you can combine the regex approach with this API approach. This is the way to build a practical email validation logic for web applications.

Benefits and Drawbacks


Benefits:

  1. Simplicity of implementation: Since JQuery can directly interact with the DOM element, it is a simpler option for validating email addresses in traditional web applications.
  2. Baked in default validation: The basic email format validation is incorporated in the frontend itself. Therefore this approach avoids unnecessary round trips to the backend to validate the email addresses and avoids garbage data. It also fosters a good separation of responsibility between the frontend and backend in validating different aspects of the email addresses.

Drawbacks:

  1. Incompatible with web frameworks: Modern web frameworks like React, abstract away the DOM and hide it from direct programming access. Therefore JQuery cannot be used within such web applications built with React. The same applies to web applications built with Angular, Vue, and other single-page web frameworks.
  2. Performance: JQuery is suited for less complex web development and backward browser compatibility. This goes against performance. Therefore JQuery applications may experience  performance degradation compared to modern web frameworks.  

Common Issues and Solutions

  1. Responsiveness: In case of submitting many email addresses together, the server may be slow to respond as it has to perform email address validation for each address individually, before responding. In such cases, it makes sense to perform on-the-fly validation, such that every email address is sent for validation after it is entered by the user. This makes the application more dynamic and responsive.
  1. Input data validation: There is a possibility of entering email addresses with capital letters. Since email addresses are case agnostic, it is important to normalize them by converting them to lowercase, before submitting them to the server for validation and further storage.
  1. Handling typos: Such applications are subjected to a lot of typos, wherein a user input results in the wrong email address altogether. If the typo is in the domain part of the email address, then it can be auto-corrected using some fuzzy matching or AI-based email domain-checking algorithm.
  1. Regulatory compliance: Email address comes under the personal data of a user. Collecting such data from users calls for regulatory compliance in certain regions of the world, such as GDPR compliance in Europe. Therefore, the application backend should Implement secure practices for data storage and processing, and obtain explicit user consent when necessary.

Conclusion

Validating multiple email addresses is not a very common scenario in most web applications. However, for marketing and customer support-centric applications that rely on the use of multiple email addresses for every correspondence,  having a custom UI for entering multiple email addresses at the same time eases the workflow of the user by a great deal.

If you are using JQuery within your application,  it offers a plethora of plugins for this purpose, and you have seen how easy it is to integrate within your application. But more importantly, you have to pay attention to the actual validation logic so that your email address list does not become a trash list with tons of spurious email addresses. That’s where Abstract’s Free Email Validation and Verification API comes in to help you build a robust and ironclad email validation logic.  

FAQ

How can I validate multiple email addresses in JQuery?

Email validation is not something that is in the scope of JQuery since it relies on JavaScript and JavaScript itself can be used for that purpose. However, you can validate multiple email addresses in JQuery by using a JQuery UI plugin. There are multiple UI widgets available on JQuery plugin sites such as https://www.jqueryscript.net/ that list hundreds of plugins including a few multiple email validation plugins also. For implementing foolproof validation, you also need an email validation service that offers multiple levels of checks to ensure a valid domain, MX record, and SMTP hosting for email addresses. AbstractAPI’s Email Validation and Verification API offers such a service, which can integrate with any web application running on JQuery or JavaScript.  

Can I use Regex for email validation in JQuery?

Regex can be used as part of the standard JavaScript constructs for validating email addresses. It can also be used on the server side, after receiving the email address via an AJAX request from JQuery. However, regex can only validate the standard email address format. It cannot ascertain whether the email address is legitimate or not. For this purpose, it is best to use an email validation API service like Abstract API’s Email Validation and Verification API which offers a foolproof way of checking the legitimacy of every email address.

What are the common issues faced while validating email addresses using JQuery?

There are a few ways to validate email addresses. If validation is done using regex then it is only limited to email address format check. In this case, the main issue is about the deliverability of the email address, since a valid email format can still be undeliverable due to spurious input or typos in the email ID during data entry. This problem can be addressed by leveraging an API service like AbstractAPI’s Email Validation and Verification API. Additionally, the email address validation should take into consideration the normalization aspect to ensure that all email addresses are in lowercase.  In case of bulk email address validation using JQuery, it is better to optimize the AJAX calls so that the frontend can internally send each email address for validation, instead of sending them in bulk, to prevent server flooding and delayed responses.  

4.6/5 stars (8 votes)

Shyam Purkayastha
Shyam Purkayastha is a proficient web developer and PHP maestro, renowned for his expertise in API creation and integration. His deep knowledge of PHP scripting and backend development enables him to build scalable server-side applications. Shyam is particularly passionate about RESTful API design, significantly enhancing web service functionality and data interoperability.
Get your free
Email Verification API
API
key now
Enhance the accuracy and reliability of your email validation process by trying the Abstract Email Validation API today. Don't miss out on the opportunity to streamline your email management with this powerful and efficient tool!
get started for free

Related Articles

Get your free
API
Email Verification API
key now
4.8 from 1,863 votes
See why the best developers build on Abstract
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
No credit card required