how to check if email already exists in database using javascript with code examples

Email has become a crucial part of communication in the digital world. Websites that require users to register usually ask for their email address. However, as users can have multiple email addresses, it is important for web developers to make sure that they do not allow a user to create multiple accounts with the same email address. This is where email validation comes in handy.

In this tutorial, we will learn how to check if an email already exists in a database using JavaScript with code examples.

  1. Requirements

Before we begin, there are some requirements that need to be met:

  • A database to store user information.
  • A server-side programming language (e.g. PHP, Python, Java) to interact with the database.
  • Basic understanding of JavaScript, HTML, and CSS.
  1. Creating a Database

For this tutorial, we will use MySQL as our database management system. Below is an example of a database table for storing user information:

  name VARCHAR(50) NOT NULL,
  email VARCHAR(50) NOT NULL,
  password VARCHAR(50) NOT NULL

This table has four columns – id, name, email, and password. For the purpose of this tutorial, we will focus only on the email column.

  1. Creating a Server-Side Script

Now that we have a database, we need to create a server-side script to interact with the database. In this tutorial, we will use PHP.

Create a file called check_email.php and add the following code:


$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);

$email = $_POST['email'];

// Check if email already exists
$sql = "SELECT * FROM users WHERE email='$email'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  echo "Email already exists";
} else {
  echo "Email does not exist";



This script connects to the database, retrieves the email address submitted via a POST request, and checks if it already exists in the database table. If it does, it returns a message saying "Email already exists". Otherwise, it returns a message saying "Email does not exist".

  1. Creating the HTML Form

In order to check if an email already exists in the database, we need to create an HTML form where users can enter their email addresses. Create a file called index.html and add the following code:

<!DOCTYPE html>
  <title>Check Email</title>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email">
    <input type="button" value="Check" onclick="checkEmail()">

  <div id="result"></div>

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

This form has an input field for the user to enter their email address and a button to trigger the email validation. The form also has a div called "result" which will display the validation result. Finally, we have added a script tag to include our JavaScript file called check_email.js.

  1. Creating the JavaScript Validation

Now it's time to write the JavaScript code to handle the form submission and validate the email address. Create a file called check_email.js and add the following code:

function checkEmail() {
  var email = document.getElementById("email").value;
  var xmlhttp = new XMLHttpRequest();

  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("result").innerHTML = this.responseText;
  };"POST", "check_email.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("email=" + email);

This code retrieves the email address entered by the user from the input field, creates a new XMLHttpRequest object, and sends a POST request to the check_email.php script we created earlier. The email address is sent as a parameter in the request body.

The onreadystatechange event is used to handle the response from the server. If the response status is 200 (OK), the validation result is displayed in the "result" div.

  1. Testing the Email Validation

We're now ready to test our email validation. Open index.html in a web browser and enter an email address in the input field. Click the "Check" button, and you should see a message saying "Email does not exist" or "Email already exists" based on whether the email address is already in the database or not.

Congratulations! You have successfully checked if an email already exists in a database using JavaScript with code examples.

Sure! Here is some additional information about the previous topics covered in this article.

Creating a Database

While the example database used in this article is MySQL, there are many other options available for database management systems. Some popular alternatives include PostgreSQL, SQLite, and Microsoft SQL Server.

It is important to design your database schema carefully, taking into account the various relationships between your data entities. This will help ensure that your database is organized efficiently and can handle large volumes of data without becoming unnecessarily complex.

Creating a Server-Side Script

When working with server-side scripts, it is important to keep security in mind. Be sure to sanitize any user input to prevent SQL injection attacks and other types of malicious activity.

In addition, consider using a modern web framework like Laravel or Ruby on Rails to simplify your server-side coding and speed up your application development process.

Creating the HTML Form

HTML forms are a key mechanism for soliciting user input on the web. They can be used for a wide variety of purposes, from collecting user data to submitting payment information for online transactions.

When designing your HTML forms, be sure to consider the user experience. Keep forms simple, clear, and visually appealing to encourage users to submit their information.

Creating the JavaScript Validation

JavaScript is a powerful language for implementing client-side validation and interactivity on the web. However, it is important to use JavaScript wisely to avoid negatively impacting page load times and other performance issues.

Consider using a JavaScript library like jQuery, ReactJS, or AngularJS to simplify your development process and make your code more efficient and maintainable.

Testing the Email Validation

Testing your email validation is a critical step in ensuring that your application functions properly and responds correctly to user input. Be sure to test your application on multiple devices and web browsers to ensure compatibility and avoid any unexpected surprises.

To streamline your testing process, consider using a testing framework like Selenium or Testim to automate your testing activities and optimize your test coverage.

In conclusion, there are many elements to consider when building a modern web application. By following best practices for database design, server-side scripting, HTML form design, JavaScript validation, and testing, you can create a powerful and effective application that meets the needs of your users and drives your business forward.

Popular questions

  1. What is the purpose of validating an email address in a database?
    A: The purpose of validating an email address in a database is to prevent users from creating multiple accounts using the same email address, and to ensure that email addresses entered by users are valid and correctly formatted.

  2. Which database management system is used in the code examples provided?
    A: The code examples provided use MySQL as the database management system.

  3. What is the purpose of the server-side script in this tutorial?
    A: The server-side script in this tutorial is responsible for retrieving the email address submitted by the user via a POST request and checking whether it already exists in the database table.

  4. What is the purpose of the XMLHttpRequest object in the JavaScript validation code?
    A: The purpose of the XMLHttpRequest object is to send a POST request to the server-side script and handle the response that is returned.

  5. What are some best practices for testing email validation in a web application?
    A: Some best practices include testing on multiple devices and web browsers to ensure compatibility, using a testing framework to automate testing activities and optimize test coverage, and performing regular security audits to ensure that user data is being handled securely.



As a developer, I have experience in full-stack web application development, and I'm passionate about utilizing innovative design strategies and cutting-edge technologies to develop distributed web applications and services. My areas of interest extend to IoT, Blockchain, Cloud, and Virtualization technologies, and I have a proficiency in building efficient Cloud Native Big Data applications. Throughout my academic projects and industry experiences, I have worked with various programming languages such as Go, Python, Ruby, and Elixir/Erlang. My diverse skillset allows me to approach problems from different angles and implement effective solutions. Above all, I value the opportunity to learn and grow in a dynamic environment. I believe that the eagerness to learn is crucial in developing oneself, and I strive to work with the best in order to bring out the best in myself.
Posts created 2361

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top