Back to Homepage
Wednesday 7 August 2024
7

How to validate email in javascript

Why Validate Email Addresses?

Validating email addresses helps to:

  • Ensure data integrity by accepting only properly formatted email addresses.
  • Reduce the chances of errors in user input.
  • Prevent fake or incorrect email addresses from being submitted, enhancing the quality of data.

Basic Email Validation Using Regular Expressions

Regular expressions (regex) provide a powerful way to validate email addresses. A well-crafted regex can accurately match valid email formats.

Example of a Simple Email Validation Regex

Here's a basic example of a regex for validating email addresses:

function validateEmail(email) {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(email);
}

// Example usage
console.log(validateEmail('test@example.com')); // true
console.log(validateEmail('invalid-email')); // false

Explanation of the Regex

  • ^[^\s@]+: Ensures the email starts with one or more characters that are not spaces or @ symbols.
  • @: Matches the @ symbol.
  • [^\s@]+: Ensures one or more characters that are not spaces or @ symbols follow the @.
  • \.: Matches a dot (.).
  • [^\s@]+$: Ensures one or more characters that are not spaces or @ symbols follow the dot and end the string.

Advanced Email Validation Regex

For more stringent validation, you can use a more complex regex that adheres closely to the email format standards defined in RFC 5322.

function validateEmail(email) {
  const re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return re.test(email);
}

// Example usage
console.log(validateEmail('test@example.com')); // true
console.log(validateEmail('invalid-email')); // false

Explanation of the Advanced Regex

  • ^[a-zA-Z0-9._%+-]+: Matches one or more alphanumeric characters, dots (.), underscores (_), percentage signs (%), plus signs (+), or hyphens (-) at the beginning.
  • @: Matches the @ symbol.
  • [a-zA-Z0-9.-]+: Matches one or more alphanumeric characters, dots (.), or hyphens (-) following the @.
  • \.: Matches a dot (.).
  • [a-zA-Z]{2,}$: Matches two or more alphabetic characters at the end.

Real-Time Email Validation in Form Input

You can implement real-time email validation in a form input field using JavaScript event listeners.

Example of Real-Time Validation

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Email Validation</title>
  <style>
    .error {
      border-color: red;
    }
    .success {
      border-color: green;
    }
  </style>
</head>
<body>
  <form id="emailForm">
    <label for="email">Email:</label>
    <input type="email" id="email" name="email">
    <span id="emailError" style="color: red;"></span>
    <button type="submit">Submit</button>
  </form>

  <script>
    document.getElementById('email').addEventListener('input', function() {
      const emailInput = this;
      const emailError = document.getElementById('emailError');
      const emailValue = emailInput.value;
      const isValid = validateEmail(emailValue);

      if (isValid) {
        emailInput.classList.remove('error');
        emailInput.classList.add('success');
        emailError.textContent = '';
      } else {
        emailInput.classList.remove('success');
        emailInput.classList.add('error');
        emailError.textContent = 'Invalid email address';
      }
    });

    function validateEmail(email) {
      const re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      return re.test(email);
    }
  </script>
</body>
</html>

In this example:

  • The email input field is validated in real-time as the user types.
  • The border color of the input field changes to red for invalid email addresses and green for valid ones.
  • An error message is displayed below the input field for invalid email addresses.

Using HTML5 Email Validation

HTML5 provides built-in email validation using the type="email" attribute. This can be combined with JavaScript for enhanced validation.

Example Using HTML5 Email Validation

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Email Validation</title>
</head>
<body>
  <form id="emailForm">
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    <span id="emailError" style="color: red;"></span>
    <button type="submit">Submit</button>
  </form>

  <script>
    document.getElementById('emailForm').addEventListener('submit', function(event) {
      const emailInput = document.getElementById('email');
      const emailError = document.getElementById('emailError');

      if (!emailInput.validity.valid) {
        emailError.textContent = 'Please enter a valid email address';
        event.preventDefault();
      } else {
        emailError.textContent = '';
      }
    });
  </script>
</body>
</html>

In this example:

  • The HTML5 type="email" attribute provides basic validation.
  • JavaScript checks the validity state of the input field on form submission.
  • An error message is displayed if the email address is invalid.

Conclusion

Validating email addresses in JavaScript is essential for ensuring data quality and preventing errors. By using regular expressions, real-time validation, and HTML5 built-in validation, you can effectively validate email addresses in your web applications. Choose the method that best suits your needs and enhance your forms with robust email validation.

Share:
Created by:
Author photo

Jorge García

Fullstack developer