Vanilla JavaScript Email Validation

β€” 5 minute read

permalink

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 ensure the email input is a valid email address with pure 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>
</div>

JavaScript Validating an Email Address permalink

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

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

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

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

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

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 =
/^(([^<>()\[\]\\.,;:\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 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 permalink

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