Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Validate an Email in ReactJS?
Email validation is an important feature we need to add to authentication forms. 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 themselves.
Also, we need to validate the email while getting the user's email via contact forms. The user may enter the wrong email format due to some mistake. To correct users' mistakes, we can alert them by showing an error message.
Below, we will learn two approaches to validate email addresses in ReactJS using different methods.
Using the validator npm package
The validator NPM package is a library module in ReactJS. We can install it in our project and use it by importing it.
First, install the validator npm package using the following command in your project directory:
npm i validator
The validator module contains various methods to validate email, phone numbers etc. We can use the isEmail() method which returns a boolean value based on whether the email is valid.
Syntax
if (validator.isEmail(email)) {
// email is valid
} else {
// email is not valid
}
Example
In the example below, we have created a user input to take an email from users. Whenever changes occur in the input field, it invokes the handleEmail() function.
<html>
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://unpkg.com/validator@13.7.0/validator.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState } = React;
const App = () => {
const [email, setEmail] = useState("test@gmail.com");
const [message, setMessage] = useState("");
function handleEmail(event) {
let newEmail = event.target.value;
setEmail(newEmail);
if (!validator.isEmail(newEmail)) {
setMessage("Please, enter a valid email!");
} else {
setMessage("");
}
}
return (
<div style={{padding: "20px"}}>
<h2>
Validate email using validator npm package
</h2>
<div style={{color: "red", minHeight: "20px"}}>
{message}
</div>
<input
type="email"
value={email}
onChange={handleEmail}
style={{padding: "5px", margin: "10px 0"}}
/>
<div>The email entered is: {email}</div>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
</script>
</body>
</html>
Using Regular Expression
Regular expression is a pattern of characters that we can use to validate email format. We create a regex pattern and use the test() method to check whether an email matches the email pattern.
Syntax
let emailRegex = /[a-z0-9]+@[a-z]+\.[a-z]{2,3}/;
if (!emailRegex.test(inputValue)) {
// invalid email
} else {
// valid email
}
Regular Expression Breakdown
/ /- Represents the start and end of the regular expression[a-z0-9]+- At least one character between a-z and 0-9@- Email must contain @ character[a-z]+- At least one character after '@'\.- Validates the dot after domain name[a-z]{2,3}- Two or three characters after the final dot
Example
<html>
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState } = 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 style={{padding: "20px"}}>
<h2>
Validate email using regular expression
</h2>
<div style={{color: "red", minHeight: "20px"}}>
{message}
</div>
<input
type="email"
value={email}
onChange={handleEmail}
style={{padding: "5px", margin: "10px 0"}}
/>
<div>Your email is: {email}</div>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
</script>
</body>
</html>
Comparison
| Method | Pros | Cons |
|---|---|---|
| Validator Package | Tested by community, comprehensive validation | External dependency |
| Regular Expression | No external dependency, customizable | Complex patterns, may miss edge cases |
Conclusion
Both methods effectively validate email addresses in ReactJS. The validator package provides robust, tested validation, while regular expressions offer customization without external dependencies. Choose based on your project requirements and complexity needs.
