Site icon Mailtrap

How to Validate Emails in React

Try to wrap your mind around this fact: 10% of email addresses entered into checkouts and sign up forms are invalid. Then, think about how mobile traffic has drastically increased in the last couple of years, and imagine the number of invalid email addresses entered via a mobile device. Since “mobile” usually goes hand in hand with “fat fingers”. 

These two simple facts remind us that email validation is still a “thing”, and it is absolutely essential to validate email address input in any registration form.

Email validation VS email verification: what you need to know

While email validation may be part of the email verification process, they are not the same. Be careful not to mix them up and not to use them interchangeably.

Email validation is a procedure that helps identify if an email address is free of typos. Basically, email validation aims to detect and prevent typos and invalid email addresses being entered into any forms. Email validation is mostly (but not always) done at the frontend.

Email validation is used:

Email verification is a process that helps verify if there is an actual user on the receiving end of the email address. Email validation could be part of email verification (and it usually is), however email verification is a more complex procedure involving both frontend and backend. To verify an email address properly, you will need to send an activation link/code to that email. Then the end user should activate it from their inbox: and we are talking about email confirmation here. When sending emails for a multilingual campaign, also validate React localization to ensure that all content elements are translated correctly.

Email verification is used:

Email validation aka input validation 

A valid email address consists of three parts: an individual part, the at-sign @, and a domain name part. If any of these parts are missing, misspelt, or misplaced, an email address becomes invalid.

According to the specifications of most Internet mail systems, the individual (local) part of an email address may consist only of the following ASCII standard characters:

The domain name part comprises of the following characters:

So how to validate email format in React.js?

There are a lot of methods. We’ll discuss a few of the most popular ones.

Email validation regex in React.js

Whichever method of email validation in React.js you choose, you cannot do without a regular expression. It is also called validation regex or regular expression. Regex is a pattern used to match character combinations in strings. Mind that in JavaScript, regex is also an object.

Validation regex is used in all React form validation libraries, it is also essential to your individual email validation solution. Let’s just say validation regex is a must whenever you need to validate any form.

Normally, React email validation regex  would look something like this:

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

Which is kind of scary, but each component of this expression has its meaning targeted at verifying the input of digits, characters, and letters of email address parts.

Email validation as part of form validation in React. Js

There are plenty of ways you can perform email validation in React.js. In fact, you can even create your own library for this purpose! However, there is no need to reinvent the wheel. One of the coolest things about React is that you can use suitable tooling for almost everything you  want 🙂

Email validation in React.js could be seen as part of a more general context: form management and form validation. There are plenty of libraries to manage forms in React  such as Formik, React Final Form, Unform, React Form, Simple React Validator etc. In this article, I’ll show you how to validate email addresses with the two of them:  Formik and React Hook Form.

Method one: email validation with Formik library

Formik is a React and React Native library that helps you create and validate forms in React “without the tears”.

First, you need to install Formik:

npm i formik

Then add the useFormik hook to manage submissions, and changes in email inputs in the src/App.js :

import { useFormik } from 'formik';

Then structure the useFormik hook:

const formik = useFormik({
  initialValues: {
    email: '',
  },
  validate,
  onSubmit: (values) => {
    alert(JSON.stringify(values, null, 2))
  },
})

where initialValues is an object containing the default values, and onSubmit is the function that is called when the email form validation passes.

validate is our separate validation function, that is in charge of handling our form validation per se.

Here’s how you code the validate function:

const validate = (values) => {
  const errors = {}

  if (!values.email) {
    errors.email = 'Required'
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address'
  }

  return errors
}

This is how the entire piece of code would look like (where the return function obviously returns the pre-coded form after validation):

import React from 'react';
import { useFormik } from 'formik'

const validate = (values) => {
  const errors = {}

  if (!values.email) {
    errors.email = 'Required'
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address'
  }

  return errors
}

export default function App() {
  const formik = useFormik({
    initialValues: {
      email: '',
    },
    validate,
    onSubmit: (values) => {
      alert(JSON.stringify(values, null, 2))
    },
  })
return (
      <form onSubmit={formik.handleSubmit}>
          <label htmlFor="email">Email</label>
          <input type="email" name="email" id="email"
            onChange={formik.handleChange} onBlur={formik.handleBlur} value={formik.values.email} />
          {formik.touched.email && formik.errors.email ? (
            <span>{formik.errors.email}</span>
          ) : null}
          <button type='submit'>Submit</button>
      </form>
  );
}
// or any of your form created previously

Method two: email validation with React Hook Form library

React Hook Form is famous for its simple and highly preformative validation solutions. It allows you to add form validation to HTML input elements with bare minimum lines of code. 

Now, let’s see how it works. 

First, you need to install the library:

npm install react-hook-form

Second, get to understand the two basic functions crucial to the process of email validation:

useForm

This one is to call the hook, and it contains all the parameters you need to validate an email address.

register()

This one registers the field and all the validation options so that useForm could operate and run validation.

The entire code for email validation will with React Hook library look like this:

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

export default function App() {
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm();
  const onSubmit = (values) => alert(JSON.stringify(values, null, 2));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        type="text"
        placeholder="Email"
        {...register("email", { required: true, pattern: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i })}
      />
      {errors.email && <span>Invalid email</span>}

      <input type="submit" />
    </form>
  );
}

But let me give you a hint. The team behind React Hook library is one of the nicest in the world. Not only have they created the detailed documentation with examples, but also a form validation builder. So, all you need to do is go there, and grab your ready-made email validation code lines.

Method three: validate email format with the validator module 

Another way to verify whether email address input is valid or not is by using the validator module in your React app. It’s pretty straightforward. Just follow this example:

Install the validator module to your React app.

npm install validator

We won’t go into UI details here, so the email form will look as basic as it can be. 

In your App.js file write the following lines of code:

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

export default function App() {
  const [message, setMessage] = useState("");
  const validateEmail = (e) => {
    const email = e.target.value;

    if (validator.isEmail(email)) {
      setMessage("Thank you");
    } else {
      setMessage("Please, enter valid Email!");
    }react
  };

  return (
    <div>
      <h2>Validating Email in ReactJS</h2>
      <label htmlFor="userEmail">Enter Email:</label>
      <input
        type="text"
        id="userEmail"
        onChange={(e) => validateEmail(e)}
      ></input>
      <br />
      <span
        style={{
          fontWeight: "bold",
          color: "red"
        }}
      >
        {message}
      </span>
    </div>
  );
}

Finally, run the app from the root directory with the npm start to see how it works.

Add CSS and go fancy with the UI/UX if you need it.

Method four: write your own code lines (because why not?)

Yes, we know there might be a thousand and one reasons why you need to manually validate email format with React.js. We’ll go for the one that is simple and written to speed up the process of validation. 

Let’s now see how it’s done.

import React, { useState } from "react";
 
const isEmail = (email) =>
  /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(email);
 
export default function App() {
  const [values, setValues] = useState({ email: "" });
  const [errors, setErrors] = useState({});
 
  const validateAndSubmitForm = (e) => {
    e.preventDefault();
 
    const errors = {};
 
    if (!isEmail(values.email)) {
      errors.email = "Wrong email";
    }
 
    setErrors(errors);
 
    if (!Object.keys(errors).length) {
      alert(JSON.stringify(values, null, 2));
    }
  };
 
  const setEmail = (e) => {
    setValues((values) => ({ ...values, email: e.target.value }));
  };
 
  return (
    <form onSubmit={validateAndSubmitForm}>
      <h2>Validating Email in ReactJS</h2>
      <span>Enter Email: </span>
      <input
        type="text"
        id="userEmail"
        value={values.email}
        onChange={setEmail}
      />{" "}
      <input type="submit" />
      <br />
      {Object.entries(errors).map(([key, error]) => (
        <span
          key={`${key}: ${error}`}
          style={{
            fontWeight: "bold",
            color: "red"
          }}
        >
          {key}: {error}
        </span>
      ))}
    </form>
  );
}

Instead of conclusion

There are numerous ways to validate email in React.js. In general, it is recommended to use libraries for complex forms containing email validation. Libraries are speedy solutions for standard but sophisticated validations. 

Write your own coding solution for email validation in React.js in the following cases: when the form is very simple (it saves time and ensures speedy download), and when the form requires flexibility or an extraordinary approach to email validation.

And remember to avoid confusion between email validation with email verification. 

Stay calm and React.js.

Exit mobile version