DEV Community

Cover image for How to Implement Real-Time Email Validation
Ryoichi Homma
Ryoichi Homma

Posted on

How to Implement Real-Time Email Validation

Validating email addresses in real time can significantly enhance the user experience and ensure the accuracy of data in your system. In this article, you'll learn how to integrate the ZeroBounce API into your web application to validate email addresses as users type them into a form.

What is ZeroBounce?

ZeroBounce is a powerful email validation and deliverability platform that helps developers and businesses verify email addresses. By integrating their API, you can:

  • Reduce bounce rates.
  • Improve email list quality.
  • Prevent spam signups.

Let's dive into how to set up real-time email validation with ZeroBounce in a React application.

Prerequisites

Before you begin, ensure you have the following:

  • A basic understanding of React.
  • Node.js installed on your local machine.
  • A ZeroBounce account and API key.

Setting Up the Project

1. Create a React App

First, create a new React app using Vite or Create React App command. I'll follow Vite here:

npm create vite@leatest real-time-email-validation --template
cd real-time-email-validation
npm install
Enter fullscreen mode Exit fullscreen mode

2. Install Axios

Install Axios for making HTTP requests:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Building the Contact Form

Create a simple contact form to capture user input and validate the email address.

1. Build the Form Component

Create a ContctForm component to handle user input and fetch the API.

import React, { useState} from 'react'; 
import axios from 'axios'; 

const ContactForm = () => {
  const [email, setEmail] = useState("");
  const [validationMessage, setValidationMessage] = useState(null);
  const [error, setError] = useState(null);

  const validateEmail = async () => {
    try {
       const response = await axios.get(
         `https://api.zerobounce.net/v2/validate?api_key=YOUR_API_KEY&email=${email}`

       if (response.data.status === 'valid') {
         setValidationMessage('Email is valid.');
       } else {
         setValidationMessage('Invalid email address.');
       } 
    } catch (err) {
      console.log('Error validating email:', err);
      setError('Unable to validate email at the moment.');
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    setValdationMessage(null);
    setError(null);
    validateEmail();
  };

  return (
    <form onSubmit={handleSubmit} >
      <>
        <label htmlFor='email'>Email:</label>
        <input 
          id='email'
          type='email'
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
         />
      </>
      <button type='submit'>Validate Email</button>
      {validationMessage && <p>{validationMessage}</p>}
      {error && <p style={{ color: 'red' }}>{error}</p>}
    </form>
  );
};

export default ContactForm;
Enter fullscreen mode Exit fullscreen mode

Securing the API Key

Do not forget to secure your ZeroBounce API key so that it wouldn't be exposed to the client side. To do that, refer to my another article that provides a step-by-step tutorial, "How to Hide Only API Keys Instead of Entire Files on GitHub and From Its Commit History".

Testing the Application

  1. Replace YOUR_API_KEY in the axios.get call with your ZeroBounce API key.
  2. Start the development server:
npm run dev
Enter fullscreen mode Exit fullscreen mode
  1. Open your browser and navigate to the local server (e.g., http://localhost:5173).
  2. Enter an email address into the form and click "Validate Email". The application will display whether the email is valid or not.

Conclusion

By integrating the ZeroBounce API into your React app, you can ensure the validity of email addresses in real time. This not only improves the user experience but also helps maintain a clean and effective email list. Try implementing this solution in your next project and take your email validation to the next level!

If you found this guide helpful, feel free to leave a comment or share your thoughts! Your feedback is always appreciate!

Top comments (0)