PASSWORD RESET

Your destination for complete Tech news

How to validate an email address in React JS?

355 0
< 1 min read

You can validate an email address in React using regular expressions (regex) or using HTML5’s built-in email validation. Here are both approaches:

Using Regular Expression:

import React, { useState } from 'react';

function EmailValidation() {
  const [email, setEmail] = useState('');
  const [isValid, setIsValid] = useState(true);

  const validateEmail = (inputEmail) => {
    const emailPattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
    return emailPattern.test(inputEmail);
  };

  const handleEmailChange = (e) => {
    const newEmail = e.target.value;
    setEmail(newEmail);
    setIsValid(validateEmail(newEmail));
  };

  return (
    <div>
      <input
        type="email"
        value={email}
        onChange={handleEmailChange}
        className={isValid ? '' : 'invalid'}
      />
      {!isValid && <p className="error-message">Invalid email address</p>}
    </div>
  );
}

export default EmailValidation;

In this example, the EmailValidation component uses a regular expression to validate the email address. The validateEmail function tests the input against the regex pattern. The isValid state is used to track whether the email is valid, and an error message is displayed if it’s not.

Using HTML5 Validation:

import React, { useState } from 'react';

function EmailValidation() {
  const [email, setEmail] = useState('');

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

export default EmailValidation;

In this example, the email input uses the type="email" attribute, which automatically triggers HTML5’s built-in email validation. If the entered value is not a valid email, the browser will show an error message and prevent form submission.

You can choose either approach based on your requirements. The regex-based approach offers more control over the validation logic, while the HTML5 validation is more user-friendly and provides immediate feedback.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.