Vanilla JavaScript Email Validation

β€” 4 minute read


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 permalink

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>

JavaScript Validating an Email Address permalink

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');

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;

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());

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 😩';

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.

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

Thank you for reading, and let's connect! permalink

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