How to validate an Email in an Input field in React

The topic of today’s article will be how you can validate an email in an input field in React. You can use some of the ways mentioned in the article, such as installing the validator library or using the Formik package.

Validate an Email in an input field in React

An email address will consist of 3 parts: Format name, email name, and domain name.

+ Name format: A name to help readers identify who sent the email. But today, people often do not use the format name in their email.

+ Email Name: The name that identifies the mailbox of that email address. This name is created by the user as long as it is unique and different from other email addresses, possibly the user’s name with special characters.

+ Domain Name: The name of the email service provider. This section usually begins with an “@” and is followed by the domain name.

We already know the structure of an email. Let’s see the next part of the article to learn how to validate emails according to the above structure.

Installing the validator library 

This is a package built to do form validation in React. You can install this package using the following command:

npm install validator

After the program installs the package, we can import and code the validation part depending on the problem requirements. Specifically, here, what we have to do is validate an input card with the correct value of the email. If the user enters it wrong, it will notify the invalid email.

Code:

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

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

        if (validator.isEmail(email)) {
            setMessage("This is a valid email!");
        } else {
            setMessage("Invalid Email!");
        }
    };

    return (
        <div>
            <h2>Validate an Email in an Input field in React</h2>
            <label>Enter Your Email: </label>
            <input type="text" id="email" onChange={(e) => validateEmail(e)}></input>
            <br />
            <span
                style={{
                    fontWeight: "bold",
                    color: "red",
                }}
            >
                {message}
            </span>
        </div>
    );
}

Output:

Package validator already provides us with functions to validate different values ​​, such as validator.isEmail, to check if the passed string is an email. Like the code above, we create an input tag for the user to enter an email. When the input catches the value change event, it will continuously check if the input string is an email.

Using Formik package

In addition to the above validator library, React provides many libraries that can do the same. Formik is the best form management library today that you should use.

Before using it, you also need to install it in your project using the command below:

npm install formik

After running the command, you can import components from the package to validate the email input that we need to validate.

Code:

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

const validate = (values) => {

    const errors = {}

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

    return errors
}

export default function App() {
    const formik = useFormik({
        initialValues: {
            email: "",
        },
        onSubmit: () => {
            console.log("Your email was sent!!")
        },
        validate,
    })

    return (
        <div>
            <form onSubmit={formik.handleSubmit}>
                <div>
                    <h2 htmlFor="email">Enter your mail</h2>
                    <input type=" email" name="email" id="email"
                        onChange={formik.handleChange} value={formik.values.email} />
                    {formik.touched.email && formik.errors.email && (
                        <span>{formik.errors.email}</span>
                    )}
                    <button type='submit'>Send</button>
                </div>
            </form>
        </div>
    );
}

Output:

In this way, we need to put the email input tag in a form so that we can use the formik to validate. Wish you success with the methods in the article

Summary

The article has shown you how to validate an Email in an input field in React. You can use any validation library that React supports, but it needs to be tailored to the requirements of the project and the client.

Leave a Reply

Your email address will not be published. Required fields are marked *