In this article, we are going to learn how to validate email addresses in Reactjs.
What is a web application without forms, they are the most efficient ways to collect user data, from the login/signup to the feedback, we use forms frequently as a frontend developer.
While collecting the data, we want to validate them first to make sure we are getting the right input that we have asked for.
In React, we can create an input element and then make it a controlled component by defining its state and updating the state’s value when anything changes on the input.
While updating the state, we can have a function that will validate the input’s value to check if it is a valid email or not.
To validate the email, we are going to make use of regular expressions as they are the most convenient way to check if the string follows a certain pattern or not.
We will debounce the validation check to make sure that the check is invoked only when the users stop typing for a certain amount of time (Assuming they are done with their thought process).
For the validation, we will have another state to monitor the validation, which will be false by default, if the input HTML has any value and that value is failing the email check then we will update the validation state to true, otherwise we will set it to false.
And then based on the validation state we will show an error message below the input field stating “Please enter a valid email address”.
This validation you can have at both form input change and the submit button press as per your convenience.
import { useState, useCallback } from "react"; import "./styles.css"; import { debounce } from "lodash"; export default function App() { // store the email address const [email, setEmail] = useState(""); // store the valid state of email const [invalidEmail, setInvalidEmail] = useState(false); // helper function that checks email using regex const isValidEmail = (email) => { return /(?!.*\.{2})^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i.test( email ); }; // function to validate email const validateEmail = (text) => { if (!!text && !isValidEmail(text)) { setInvalidEmail(true); } else { setInvalidEmail(false); } }; // debounce the function to initiate test // when user stops writing for certain time const debouncedValidateEmail = useCallback(debounce(validateEmail, 1000), []); // email change handler // stores the email and validates it const emailChangeHandler = (e) => { setEmail(e.target.value); debouncedValidateEmail(e.target.value); }; return ( <div className="App"> <div className="field-area"> <label>Email: </label> <input type="email" name="email" placeholder="Your email please" value={email} onChange={emailChangeHandler} /> {invalidEmail && <p>Please enter a valid email address</p>} </div> </div> ); }