Open In App

How to Validate an Email in ReactJS ?

Last Updated : 09 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Validating email in React is an important step to authenticate user email. It ensures the properly formatted email input from the user. The following example shows how to validate the user entered email and checking whether it is valid or not using the npm module in React Application.

Approach

To validate an email in React we will use the validator npm package. Take the email input from users and validate the input using validator.isEmail() function. This function returns boolean value. Display the message “Valid Email” if it gives true else return the message “Enter valid Email”.

Syntax:

const validateEmail = (e) => {
const email = e.target.value;

if (validator.isEmail(email)) {
return "Valid Email :)";
} else {
return "Enter valid Email!";
}
};

Steps to Create React Application and Install Module

Step 1: Create a React application using the following command:

npx create-react-app emailvalidatordemo

Step 2: After creating your project folder i.e. emailvalidatordemo, move to it using the following command:

cd emailvalidatordemo

Step 3: After creating the React application, Install the validator module using the following command:

npm install validator

Project Structure:

Project Structure

The updated dependencies in the package.json file are:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"validator": "^13.12.0",
"web-vitals": "^2.1.4"
},

Email validation is a common requirement for user registration forms.

Example: This example uses the validator npm package to validate date in React app.

JavaScript
// Filename - App.js

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

const App = () => {
	const [emailError, setEmailError] = useState("");
	const validateEmail = (e) => {
		const email = e.target.value;

		if (validator.isEmail(email)) {
			setEmailError("Valid Email :)");
		} else {
			setEmailError("Enter valid Email!");
		}
	};

	return (
		<div
			style={{
				margin: "auto",
				marginLeft: "300px"
			}}
		>
			<pre>
				<h2>Validating Email in ReactJS</h2>
				<span>Enter Email: </span>
				<input
					type="text"
					id="userEmail"
					onChange={(e) => validateEmail(e)}
				></input>{" "}
				<br />
				<span
					style={{
						fontWeight: "bold",
						color: "red"
					}}
				>
					{emailError}
				</span>
			</pre>
		</div>
	);
};

export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

Output---Email-validation-in-react


Next Article

Similar Reads