How to Validate Email Format with JavaScript (Beginner Guide)

Validating an email format is one of the most common and important tasks in web forms. With JavaScript, you can easily check if the user entered a valid email before submitting the form.

In this tutorial, you’ll learn how to validate email format with JavaScript step by step, using regular expressions (RegEx) in a simple and beginner-friendly way.


👁️ Preview


🧱 Step 1: Basic HTML Form

<form id="emailForm">
  <label for="email">Email:</label>
  <input type="text" id="email" placeholder="example@email.com" />
  <button type="submit">Submit</button>
  <p id="message"></p>
</form>

🎨 Step 2: Basic Styling (Optional)

input, button {
  padding: 10px;
  margin: 10px 0;
  width: 100%;
  max-width: 300px;
  box-sizing: border-box;
}

#message {
  font-weight: bold;
  color: red;
}

⚙️ Step 3: JavaScript Email Validation

document.getElementById("emailForm").addEventListener("submit", function (e) {
  e.preventDefault();

  const emailInput = document.getElementById("email").value;
  const message = document.getElementById("message");

  // Regular expression for basic email format
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  if (emailRegex.test(emailInput)) {
    message.textContent = "✅ Valid email!";
    message.style.color = "green";
  } else {
    message.textContent = "❌ Invalid email format.";
    message.style.color = "red";
  }
});

✅ Explanation

  • e.preventDefault() prevents the form from submitting.
  • emailRegex is a simple but effective pattern to check if the input looks like a valid email.
  • .test() returns true if the value matches the pattern.
  • We update the message accordingly.

🧠 Bonus Tip: Use type="email" Too!

You can add extra protection by using:

<input type="email" />

Browsers will automatically block wrong formats, but JavaScript is still useful for custom messages and logic.


✅ Final Result

Now you have a simple way to:

  • Validate email input on the client side
  • Give instant feedback to users
  • Improve the user experience and prevent invalid submissions

Leave a Comment