Guides
Last updated
July 20, 2025

5 Ways to Implement Email Validation in React

Nicolas Rios
Nicolas Rios
Table of Contents:
ON THIS PAGE
Get your free
email validation
 API key now
stars rating
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

Email validation is important for maintaining data quality in React applications. We'll explore five common ways to implement it, complete with working code snippets. We will also look at the pitfalls of these traditional methods and see how Abstract API helps overcome them.

How to Implement Email Validation in React

Here are four common methods to validate email addresses in a React application. Each approach has a different implementation, from native browser features to external libraries.

Browser Constraint Validation

React passes attributes directly to the DOM. When you render an input with `type="email"` and `required`, you get the browser's built-in pattern matching and validity API. This method works even before React hydrates, which supports progressive enhancement. It also adds zero extra bytes to your application bundle.

The code uses a `useRef` hook to get a direct reference to the input element. When the form submits, `e.preventDefault()` stops the default browser action. Then, `inputRef.current.reportValidity()` triggers the browser's validation UI. If the input is valid, you can access its value.

import { useRef } from 'react';

function EmailField() {
  const inputRef = useRef(null);

  function handleSubmit(e) {
    e.preventDefault();
    if (inputRef.current.reportValidity()) {
      // at this point inputRef.current.value is syntactically valid
    }
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <input ref={inputRef} type="email" required />
      <button>Save</button>
    </form>
  );
}

Component-Level Regular Expression

This technique involves the use of a regular expression directly inside your React component to test the email format. The pattern is stored in a constant, for example, `EMAIL_RE`. The component state manages the email input's value and any validation error message.

An `onBlur` event handler triggers the validation logic when the user moves focus away from the input field. The `EMAIL_RE.test(email)` function returns true if the email matches the pattern. Based on the result, the error state updates, and a message shows or hides. The pattern used is a common example.

import { useState } from 'react';

const EMAIL_RE = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;

function InlineRegex() {
  const [email, setEmail]   = useState('');
  const [error, setError]   = useState(null);

  function onBlur() {
    setError(EMAIL_RE.test(email) ? null : 'Invalid e-mail');
  }

  return (
    <>
      <input value={email} onChange={e => setEmail(e.target.value)}
             onBlur={onBlur} />
      {error && <span>{error}</span>}
    </>
  );
}

React-Hook-Form Pattern Rule

The `react-hook-form` library provides a `useForm` hook to manage form state and validation. It exposes a `register` function to connect inputs to the form's logic. You can declare validation rules directly in the `register` function's options object.

This includes a `required` rule for empty fields and a `pattern` rule that takes a regular expression. The library runs validation only on the fields that change, which avoids unnecessary renders. The `formState.errors` object contains any validation messages, which you can then display. This validation flow is efficient.

import { useForm } from 'react-hook-form';

function HookForm() {
  const { register, handleSubmit, formState:{ errors } } = useForm();
  return (
    <form onSubmit={handleSubmit(console.log)}>
      <input
        {...register('email', {
          required: 'E-mail is required',
          pattern : {
            value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
            message: 'Invalid e-mail'
          }
        })}
      />
      {errors.email?.message}
      <button>Go</button>
    </form>
  );
}

External Validation Library

Libraries like `validator.js` offer pre-built functions for common validation tasks. This abstracts away the complexity of regular expressions. You can install it with `npm install validator`. After you import the library, you can call functions like `validator.isEmail()` directly.

This function takes a string as an argument and returns a boolean that indicates if the string is a valid email format. In the example, the component uses an `onChange` handler to call `validator.isEmail()` on every keystroke. This provides immediate feedback to the user, as shown in this common implementation.

import validator from 'validator';
import { useState } from 'react';

function ValidatorLib() {
  const [msg, setMsg] = useState('');
  return (
    <>
      <input onChange={e =>
        setMsg(validator.isEmail(e.target.value)
               ? '✓'
               : 'Enter a valid e-mail')
      } />
      <span>{msg}</span>
    </>
  );
}

The Challenges of Email Validation

The common methods for email validation in React share fundamental limitations. They primarily check for syntax and cannot confirm if an email address actually exists or can receive mail, which creates several problems.

  • A regex that fully complies with email standards is complex and hard to maintain. Simpler patterns, used in component-level or `react-hook-form` validation, often reject valid emails or accept invalid ones, which leads to inaccurate results.
  • Browser constraint validation is inconsistent. The HTML5 specification for `type="email"` is loose, so behavior differs across browsers. This native validation can also interfere with libraries like `react-hook-form`, which causes unpredictable outcomes for the user.
  • React's asynchronous state updates create race conditions. Validation logic in controlled components might use stale state values. This results in a mismatch between client-side and server-side validation, which produces hard-to-debug errors.
  • All front-end methods, from browser validation to external libraries, only check syntax. They cannot verify if a mailbox exists or can receive emails. This check requires server-side network calls, a step beyond React's scope.

Validate Emails with Abstract API
Build a more reliable React app by implementing email validation to catch invalid user entries.
Get started for free

How Abstract API Handles Email Validation in React

Abstract API addresses the core weaknesses of traditional methods. It offloads complex server-side checks into a single, simple API call.

  • It performs comprehensive server-side checks that are impossible in a browser. These checks include syntax validation, typo correction, MX record lookups, and live SMTP handshakes.
  • The API detects disposable domains, role-based addresses, and catch-all configurations. It also provides a quality score to assess risk.
  • The JSON response provides clear, actionable data points. Developers use fields like deliverability and quality_score to build robust validation logic directly into React components.
  • It eliminates the need for developers to maintain brittle regex logic or domain lists. It also removes the security and deliverability problems of direct SMTP requests from the client.

How to Set Up Abstract API in Your Project

Once you understand Abstract’s capabilities, you can add its email validation API to your project with a few simple steps.

  • Sign up at Abstract, create an Email Validation workspace, and copy your API key.
  • Install a library like axios to handle HTTP requests, or use the native fetch API.
  • Add the API key to your .env file and restart the development server.
  • Create a dedicated function to call the Abstract API endpoint with a user's email.
  • Import and call this function from your form component on a relevant user event, like blur or submit.
  • Use the API response data, like deliverability and quality_score, to control your UI logic and provide feedback.
// validateEmail.js
import axios from 'axios';
const API_KEY = process.env.REACT_APP_ABSTRACT_EMAIL_KEY;
const base = `https://emailvalidation.abstractapi.com/v1/?api_key=${API_KEY}`;
export async function validateEmail(email) {
  const { data } = await axios.get(`${base}&email=${encodeURIComponent(email)}`);
  return data;
}

Sample Implementation with Abstract API

The validation function integrates directly into any React form component. The code below shows how to use the API response to make a decision. It checks if an email is deliverable and has a high quality score before it allows the form submission to proceed.

// EmailInput.jsx (Form library agnostic)
const handleSubmit = async value => {
  const res = await validateEmail(value);
  if (res.deliverability === 'DELIVERABLE' && res.quality_score > 0.8) proceed();
  else showError(res.autocorrect || 'Email not deliverable');
};

The API returns a detailed JSON object that empowers developers. Here is a sample response:

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

The deliverability and quality_score fields allow for an immediate go or no-go decision. Other fields like autocorrect offer typo suggestions, while flags for disposable, role, or free emails inform specific business rules. The is_mx_found and is_smtp_valid fields confirm domain and mailbox status, data points impossible to get from a browser.

Final Thoughts

Traditional client-side checks only scratch the surface and miss critical issues like disposable domains and invalid mailboxes. Abstract API replaces this fragile approach with a single, robust call that provides comprehensive, server-side analysis. To reliably validate user emails, consider an account with Abstract API and get your free API key.

Validate Emails with Abstract API
Implement proper email validation in your React app to ensure data accuracy and user trust.
Get started for free

Related Articles

Phone Validation
key now
Get your free
stars rating
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