How to validate an email in ReactJS ?
Email validation is an important step in every application in order to authenticate user email. It can be achieved using the validator module in ReactJS. 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.
Creating React Application And Installing 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: It Will look like the following.
App.js: Now write down the following code in App.js file. Here, App is our default component where we have written our code to validate email with basic UI.
Javascript
import React, { useState } from "react" ; import validator from 'validator' const App = () => { const [emailError, setEmailError] = useState( '' ) const validateEmail = (e) => { var 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:
- The following will be the output if the user enters an invalid email as shown below:
- The following will be the output if the user enters a valid email as shown below:
Contact Us