Real time email validation in javascript

142 views 3:15 pm 0 Comments December 31, 2024
Real time email validation in javascript | Email Validation Using Regular Expressions

Real time email validation in JavaScript allows you to validate an email address as the user types into the input field, enhancing the user experience by providing immediate feedback.

By giving consumers instant feedback on the legitimacy of email addresses as they write, JavaScript’s real-time email validation improves the user experience. Errors may be avoided, and data integrity can be enhanced. Here are some doable strategies for putting real-time email validation into practice.


Example of Real-Time Email Validation

Basic real-time Email Validation Using Regular Expressions

You can use a simple regex pattern to validate email addresses in real time. Here’s how you can implement it:

HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Real-Time Email Validation</title>
  <style>
    .valid {
      border: 2px solid green;
    }
    .invalid {
      border: 2px solid red;
    }
    .message {
      font-size: 14px;
      color: red;
      display: none;
    }
    .message.active {
      display: block;
    }
  </style>
</head>
<body>
  <form id="emailForm">
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" placeholder="Enter your email">
    <p id="emailMessage" class="message">Invalid email format</p>
    <br><br>
    <button type="submit">Submit</button>
  </form>

  <script>
    // Get elements
    const emailInput = document.getElementById('email');
    const emailMessage = document.getElementById('emailMessage');

    // Email validation regex
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    // Add input event listener for real-time validation
    emailInput.addEventListener('input', function () {
      const emailValue = emailInput.value;

      if (emailPattern.test(emailValue)) {
        emailInput.classList.add('valid');
        emailInput.classList.remove('invalid');
        emailMessage.classList.remove('active');
      } else {
        emailInput.classList.add('invalid');
        emailInput.classList.remove('valid');
        emailMessage.classList.add('active');
      }
    });

    // Prevent form submission if the email is invalid
    document.getElementById('emailForm').addEventListener('submit', function (event) {
      if (!emailPattern.test(emailInput.value)) {
        event.preventDefault();
        alert('Please enter a valid email address before submitting.');
      }
    });
  </script>
</body>
</html>

How It Works

  1. HTML Input Field: The <input> element listens for user input.
  2. Regular Expression: A regex (/^[^\s@]+@[^\s@]+\.[^\s@]+$/) is used to validate the email format.
  3. Real-Time Feedback:
    • As the user types, the input event checks the current value against the regex.
    • Adds a valid or invalid CSS class to the input field.
    • Displays or hides an error message dynamically.
  4. Form Submission Check: On form submission, JavaScript prevents submission if the email is invalid.

Key Features

  • Real-Time Visual Feedback:
    • Green border for valid input.
    • Red border and error message for invalid input.
  • Regex Validation: Ensures the email follows standard email formatting rules.
  • Submit Blocker: Prevents invalid data from being submitted.

Best Practices

  1. Enhance Regex for Advanced Validation: Consider stricter rules for domain validation if necessary.
  2. Accessibility: Use ARIA roles or labels to make error messages screen-reader friendly.
  3. Combine Client-Side with Server-Side Validation: Always validate the email on the server for security.
Real time email validation in javascript | Email Validation Using Regular Expressions
Real time email validation in javascript | Email Validation Using Regular Expressions

Another example of email validation in JavaScript using regular expression in real-time

<form id="emailForm">
    <label for="email">Email:</label>
    <input type="text" id="email" oninput="validateEmail(this.value)" />
    <div id="error-message" style="color:red;"></div>
</form>
<script>
  function validateEmail(email) {
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const errorMessage = document.getElementById('error-message');

    if (emailPattern.test(email)) {
        errorMessage.textContent = ''; // Clear error message
    } else {
        errorMessage.textContent = 'Invalid email format'; // Show error message
    }
}

</script>

In this example:

  • The oninput event triggers the validateEmail function every time the user types in the input field.
  • The function checks if the entered email matches the regex pattern and displays an error message if it does not.

Leave a Reply