Borislav Hadzhiev
Mon Apr 25 2022·2 min read
Photo by Elyse Turton
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.
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> ); }
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.
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.
.
, 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.