Live email validation in React (with Regex)

Last updated on October 8, 2020 Saul Goodman Loading... Post a comment

This article shows you how to validate email addresses while the user is typing in React (live validation).

Summary

  • We’ll use Javascript regular expression so that no third-party library is required.
  • We’ll use the functional component and the useState hook
  • Frontend validation is never secure enough so that you (or your team) need to implement server-side validation later.

The Steps

1. Create a new React app by running:

npx create-react-app live_email_validation

2. Remove all the default code in App.js and add this:

import React, { useState } from 'react';
import './App.css';

function App() {
  const [isValid, setIsValid] = useState(false);
  const [message, setMessage] = useState('');

  // The regular exprssion to validate the email pattern
  // It may not be 100% perfect but can catch most email pattern errors and assures that the form is mostly right
  const emailRegex = /\[email protected]\S+\.\S+/;

  const validateEmail = (event) => {
    const email = event.target.value;
    if (emailRegex.test(email)) {
      setIsValid(true);
      setMessage('Your email looks good!');
    } else {
      setIsValid(false);
      setMessage('Please enter a valid email!');
    }
  };

  return (
    <div className="container">
      <input
        type="email"
        placeholder="Enter your email"
        className="email-input"
        onChange={validateEmail}
      />

      {/*If the entered email is valid, the message will be blue, otherwise it will be red. */}
      <div className={`message ${isValid ? 'success' : 'error'}`}>
        {message}
      </div>
    </div>
  );
}

export default App;

3. Replace the default code in App.css with this:

.container {
  padding: 100px;
}

.email-input {
  width: 300px;
  padding: 5px 10px;
}

.message {
  margin-top: 20px;
  font-size: 17px; 
}

.success {
  color: blue;
}

.error {
  color: red;
}

4. Try it by running:

npm start

And here’s what you’ll see when go to http://localhost:3000 in the browser:

Done!

Related Articles

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x