Validate an Email in an Input field in React

avatar

Borislav Hadzhiev

Mon Apr 25 20222 min read

banner

Photo by Elyse Turton

Validate an Email in an Input field in React #

To validate an email in an input field in React, use the test() method on the following regular expression - /\S+@\S+\.\S+/. The test method will return true if the email is valid and false otherwise.

App.js
import {useState} from 'react'; export default function App() { const [message, setMessage] = useState(''); const [error, setError] = useState(null); function isValidEmail(email) { return /\S+@\S+\.\S+/.test(email); } const handleChange = event => { if (!isValidEmail(event.target.value)) { setError('Email is invalid'); } else { setError(null); } setMessage(event.target.value); }; return ( <div> <input id="message" name="message" value={message} onChange={handleChange} /> {error && <h2 style={{color: 'red'}}>{error}</h2>} </div> ); }

check if email is valid

We set the onChange prop on the input field, so every time its value changes, the handleChange function is invoked.

In our handleChange function, we call the isValidEmail function, passing it the email.

The Regexp.test method returns true if there is a match between the regular expression and the string, otherwise false is returned.

The forward slashes / / mark the beginning and end of the regular expression.

App:js
function isValidEmail(email) { return /\S+@\S+\.\S+/.test(email); }

The \S character matches a single character other than white space.

The + character matches the preceding character one or more times.

We used a backslash to escape the dot ., because dots have a special meaning in regular expressions.

If you ever need help reading a regular expression, check this regex cheatsheet from MDN out.

Every time the value of the input field changes, we call the isValidEmail method to check if the email is valid.

You could also do this only once - in your submit handler function, but it's common to also do it in your handle change function to provide instant feedback to the user.

Use the search field on my Home Page to filter through my more than 1,000 articles.