Vanilla JavaScript Email Validation

dailydevtips1

Chris Bongers

Posted on August 13, 2020

Vanilla JavaScript Email Validation

Today I want to address a topic I use quite often but noticed I've never written about.
Email validation! Since my day job is in marketing, we build a lot of pages with forms, and the least we need is an email address. So how do we make sure the input is at least a valid email type in JavaScript?

HTML Structure

For today's work we'll use a very simple form, with only a 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>
</div>
Enter fullscreen mode Exit fullscreen mode

JavaScript Validating an Email Address

Ok, now on to the fun part, JavaScript! Let's start by defining our variables we need to use.

var emailField = document.getElmentById('emailField');
var button = document.getElementById('button');
var response = document.getElementById('response');
Enter fullscreen mode Exit fullscreen mode

Awesome, very basic selectors, but enough for this excercise.

Now we want to add a click listener to our button.

button.addEventListener('click', function() {
  var email = emailField.value;
  console.log(email);
});
Enter fullscreen mode Exit fullscreen mode

This function will log the value of what we put in the input field.

So for now let's make our actual function to check if it's valid:

function validateEmail(email) {
  const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
}
Enter fullscreen mode Exit fullscreen mode

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

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

So let's implement this back in our button click.

button.addEventListener('click', function() {
  var 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 😩';
  }
});
Enter fullscreen mode Exit fullscreen mode

There we go! Of course, you would like to do something with this information, but I'll leave that up to you!

View this example on the following 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

💖 💪 🙅 🚩
dailydevtips1
Chris Bongers

Posted on August 13, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related