How to Validate an Email in ReactJS?


Email validation is an important feature we need to add to the authentication form. Nowadays, most applications use email and a one-time password for authentication. If the user enters the wrong email, they should not be able to authenticate their selves.

Also, we need to validate the email while getting the user's email via the contact form. The user may enter the wrong email format due to some mistake. So, to correct users' mistakes, we can alert them by showing the error that you have entered the wrong email.

Below, we will learn two approaches to validate the email address of users using two different approaches.

Use the validator npm package

The NPM package is a library module in ReactJS. We can install it in our project and use it by importing it.

Here, we need to install the validator npm package. Users can enter the below command to the terminal to install the validator npm package in the project directory.

npm i validator

The validator module contains various methods to validate email, phone numbers etc. So, we can use the isEmail() method of the validator npm package to validate the email, which returns the boolean value based on whether the email is valid.

Syntax

Users can follow the syntax below to use the validator npm package to validate the email in ReactJS.

if (validator.isEmail(new_Email)) {
// email is valid
   } else {
      // email is not valid
   }

In the above syntax, we have used the isEmail() method of the validator. Also, we have passed the new_Email as a parameter of the isEmail() method to validate.

Example

In the example below, we have created the user input to take an email from users. Whenever changes occur in the input field, it invokes the handleEmail () function.

In the handleEmail() function, we get the new input using the ‘event.target.value’ and the setEmail() to change the value of the email variable. Also, we have used the validator’s isEmail() method to validate the email we get from the users.

import React, { useState } from "react";
import validator from "validator";

const App = () => {
  const [email, setEmail] = useState("bac@gmail.com");
  const [message, setMessage] = useState(" ");
  function handleEmail(event) {
    let new_Email = event.target.value;
    setEmail(new_Email);
    if (!validator.isEmail(new_Email)) {
      setMessage("Please, enter a valid email!");
    } else {
      setMessage("");
    }
  }
  return (
    <div>
      <h2>
        {" "}
        Validate the email
        <i> using validator npm package </i>
      </h2>
      <div style = {{ color: "red" }}> {message} </div>
      <input type = "email" value = {email} onChange = {handleEmail} />
      <div> The email entered is {email} </div>
    </div>
  );
};

export default App;

Output

Use the regular expression to validate email in ReactJS

The regular expression is a pattern of characters like string. We need to follow some rules of the regular expression to create it.

We can create a regular expression to validate the email and then use the test() method to check whether an email matches the email pattern.

Syntax

Users can follow the syntax below to use the regular expression to validate email addresses in ReactJS.

let emailRegex = /[a-z0-9]+@[a-z]+\.[a-z]{2,3}/;
    if (!emailRegex.test(inputValue)) {
      // invalid email
    } else {
      // valid email
}

In the above syntax, we have taken the regular expression pattern as a reference of the test() method and passed email as a parameter of the test() method to validate.

Regular expression explanation

  • / / - It represents the start and end of the regular expression.

  • [a-z0-9]+ - It represents at least one character between a to z and 0 to 9.

  • @ - It represents that email should always contain @ character.

  • [a-z]+ – Email should always contain at least one character after ‘@’.

  • \. – It validates the dot in an email after the domain name.

  • [a-z]{2,3} – It says that email should contain either two or three characters after the dot at last.

Example

In the example below, the emailRegex variable contains the search pattern. Whenever a user enters the email input, it validates the input value using the test() method. If the test() method finds that the input is not matching, it sets the error message using the setMessage().

Users can enter the wrong email format and observe the error output in the output.

import React, { useState } from "react";

const App = () => {
  const [email, setEmail] = useState("yourmail@mail.com");
  const [message, setMessage] = useState(" ");
  function handleEmail(event) {
    let inputValue = event.target.value;
    setEmail(inputValue);

    let emailRegex = /[a-z0-9]+@[a-z]+\.[a-z]{2,3}/;
    if (!emailRegex.test(inputValue)) {
      setMessage("Error! you have entered invalid email.");
    } else {
      setMessage("");
    }
  }
  return (
    <div>
      <h2>
        {" "}
        Validate the email
        <i> using the regular expression </i>
      </h2>
      <div style = {{ color: "red" }}> {message} </div>
      <input type = "email" value = {email} onChange = {handleEmail} />
      <div> Your email is {email} </div>
    </div>
  );
};

export default App;

Output

In this tutorial, users learned to validate email in ReactJS. We used the validator NPM package and regular expression to validate the user’s email address. Using the NPM package and regular expression to validate the email address have its benefits.

When you use regular expression, you can customize it yourself to validate, and the Validator npm package provides a standard way to validate as so many developers test it.

Updated on: 08-Sep-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements