Implementing Real-Time Email Verification in React JS

In today's digital age, user experience is paramount. One crucial aspect of this experience is ensuring that users provide valid email addresses during registration or subscription processes. Real-time email verification can significantly reduce bounce rates, enhance user experience, and ensure data accuracy. In this blog post, we’ll dive into implementing real-time email verification in React JS.

Why Real-Time Email Verification Matters

Before we jump into the implementation, let's discuss why real-time email verification is essential:

  1. User Experience: Immediate feedback allows users to correct mistakes promptly.
  2. Data Quality: Ensures that only valid email addresses are entered into the database, reducing the likelihood of bounces and improving email deliverability.
  3. Security: Helps prevent misuse and spam registrations.
  4. Efficiency: Reduces the administrative burden of handling invalid email addresses.

Setting Up the React Environment

To get started, you'll need a basic React environment. If you haven't set up a React project already, follow these steps:

  1. Install Node.js: Ensure you have Node.js installed. You can download it from nodejs.org.

  2. Create a React App: Run the following command to create a new React application:

    npx create-react-app email-verification-app
    cd email-verification-app
    
  3. Start the Development Server: Navigate to the project folder and start the development server:

    npm start
    

    This should open a new browser window with your React application's default landing page.

Designing the Email Input Component

Creating a dedicated email input component allows us to encapsulate the email verification logic neatly. Start by creating a new file EmailInput.js in the src folder.

import React, { useState } from 'react';
import './EmailInput.css';

const EmailInput = () => {
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');

  const handleChange = (e) => {
    const value = e.target.value;
    setEmail(value);
    validateEmail(value);
  };

  const validateEmail = (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      setError('Invalid email address');
    } else {
      setError('');
    }
  };

  return (
    <div className="email-input">
      <input
        type="email"
        placeholder="Enter your email"
        value={email}
        onChange={handleChange}
      />
      {error && <p className="error">{error}</p>}
    </div>
  );
};

export default EmailInput;

Styling the Component

Create a new file EmailInput.css in the src folder to style the email input component:

.email-input {
  display: flex;
  flex-direction: column;
  max-width: 300px;
  margin: auto;
}

.email-input input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-bottom: 5px;
}

.email-input .error {
  color: red;
  font-size: 12px;
}

Now, you can import and use the EmailInput component in your App.js file.

import React from 'react';
import './App.css';
import EmailInput from './EmailInput';

function App() {
  return (
    <div className="App">
      <h1>Real-Time Email Verification</h1>
      <EmailInput />
    </div>
  );
}

export default App;

Adding Real-Time Verification with API

To achieve real-time verification beyond basic regex checks, we can integrate an email verification API. For this example, we will use email-verifier API.

Setting Up Email Verifier

  1. Sign Up: Register on the email-verifier website to get an API key.

  2. Install Axios: We will use Axios to make HTTP requests. Install it by running:

    npm install axios
    
  3. Update EmailInput Component: Modify the EmailInput component to include API verification logic.

import React, { useState } from 'react';
import axios from 'axios';
import './EmailInput.css';

const EmailInput = () => {
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');
  const [isVerified, setIsVerified] = useState(null); // To track verification status

  const handleChange = (e) => {
    const value = e.target.value;
    setEmail(value);
    setError('');
    setIsVerified(null);

    if (value) {
      validateEmail(value);
    }
  };

  const validateEmail = async (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      setError('Invalid email address');
    } else {
      try {
        const response = await axios.get(
          `https://api.email-verifier.io/v2/email/verify?email=${email}&api_key=YOUR_API_KEY`
        );
        const { status, info } = response.data;
        if (status === "valid") {
          setIsVerified(true);
        } else {
          setError(info || 'Invalid email address');
          setIsVerified(false);
        }
      } catch (error) {
        setError('Verification error');
        setIsVerified(false);
      }
    }
  };

  return (
    <div className="email-input">
      <input
        type="email"
        placeholder="Enter your email"
        value={email}
        onChange={handleChange}
      />
      {error && <p className="error">{error}</p>}
      {isVerified && <p className="success">Email is valid!</p>}
    </div>
  );
};

export default EmailInput;

Styling Verified Message

We can improve the user experience by providing visual feedback for valid emails as well. Update EmailInput.css to include styles for success messages:

.email-input .success {
  color: green;
  font-size: 12px;
}

Conclusion

In this comprehensive guide, we've successfully implemented real-time email verification in a React JS application. By leveraging both regular expression checks and a third-party email verification API, we provide users with immediate feedback, greatly enhancing the overall user experience and ensuring data accuracy.

Incorporating real-time email verification into your web applications can have significant benefits ranging from improved user experience to maintaining high-quality data. While email verification is just one component of user input validation, its impact on the seamless functioning of services is undeniable.

Feel free to customize this implementation further to fit your specific needs. The principles and methods illustrated here can serve as a foundation for more complex systems.

Happy coding!