How to Validate Email Addresses from Inputs in React.js


How can we validate email addresses from inputs in React.js?

We’ll be using the validator module.

1. Install validator#

Let’s install validator using npm.

npm install validator

2. Create utility function to validate email#

Let’s create a simple utility function to validate the email address.

import validator from 'validator';
const validateEmail = email => {
  return validator.isEmail(email) && email.length > 0;
}

3. Validate when email changes#

Finally, we’ll call our validateEmail() function when the email string changes.

Depending on where we store the utility function, we may have to import it from another file.

Let’s place this inside a useEffect hook that runs conditionally on email.

export default function SomeComponent() {
  const [email, setEmail] = useState("");
  const [emailValid, setEmailValid] = useState(true);
  
  useEffect(() => {
    setEmailValid(validateEmail(email));
  }, [email])

  return (
    <input
      value={email}
      onChange={e => setEmail(e.target.value)}
    />
  )
}

We can then use the emailValid boolean state to conditionally render an error message to the user.