Vanilla JavaScript Email Validation


In this tutorial we are learning how to validate an email address in JavaScript with Regex. Follow the steps and see the live demo on Codepen.

13 Aug, 2020 · 2 min read

Today I want to address a topic I use pretty often but noticed I’ve never written about:

Email validation.

Since my day job is in marketing, we build many pages with forms, and the least we need is an email address. So how do we ensure the email input is a valid email address with pure JavaScript?

HTML Structure

We’ll use a straightforward form for today’s work, with only an email input and a button to submit. Then we’ll have a response div to show us if the email was correct.

<div class="container">
  <input type="email" id="emailField" />
  <br />
  <button id="button">Check validation</button>
  <div id="response"></div>

JavaScript Validating an Email Address

Ok, now on to the fun part, the JavaScript! Let’s start by defining the variables we need to validate the email:

const emailField = document.getElmentById('emailField');
const button = document.getElementById('button');
const response = document.getElementById('response');

Fantastic, very basic CSS selectors, but enough for this exercise.

Now we want to add a click listener to the button element.

button.addEventListener('click', function () {
  const email = emailField.value;

This function will log the value from the input field to the console.

So now let’s make our actual validation function to check if it validates correctly:

function validateEmail(email) {
  const re =
  return re.test(String(email).toLowerCase());

BAM! Please don’t be scared; it’s a plain old regular expression. This will validate a valid email format.

It will return true or false, depending on the email.

So let’s implement this into our button click function.

button.addEventListener('click', function () {
  const email = emailField.value;
  if (validateEmail(email)) {
    response.innerHTML = 'Hiya Cowboy, this email will work for us 🤠';
  } else {
    response.innerHTML = 'Sorry, this email is not cool enough 😩';

There we go! This is how you validate email inputs in a form with Regex. Of course, you would like to do something with this information, but I’ll leave that up to you!

View the example code in this Codepen

See the Pen Vanilla JavaScript Email Validation by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter