DEV Community

Cover image for Vanilla JavaScript Email Validation
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

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

Top comments (4)

Collapse
 
indigo744 profile image
Guillaume

As soon as I saw the headline, I knew it would be one of these article which completely misses the point of email validation with a huge copy-pasta regex.

The only email validation worth anything is... actually sending an email and asking the user to click. So low tech, isn't it?

The best you can do on the frontend is perform a simple sanity check, like the presence of an "@". Or if you really want to be fancy, add check for misspelling of common names for a possible typo. But never deny, simply suggest.

Collapse
 
tac_token profile image
tactoken

I know this comment is around a year old, but for anyone in the future reading this, this Guillaume is so incredibly wrong its not even funny. Do not trust such horrible advice... its just plain WRONG.

So lets first assume Guillaume is correct and sanitizing an email is pointless and the only valid way is to send an email with a confirmation link. So, you as a website owner plan to display this persons email on a profile page. Others can come along and view this persons profile and see their contact information including their email address. Since the person didn't validate their email yet you display "Unconfirmed" on the profile page next to email.

So you save the persons email into a database, and you echo it out later to visitors of the site. What happens when they add an email an email such as:

openkarat script src=maliciouswebsite.com/malicious_scr... closekarat openkarat /script closekarat @doesntmatter.com

Seeing as the information is not being validated, you are about to echo back a malicious script into your website and everyone visiting that users profile is going to run that malicious script.

You should ALWAYS sanitize inputs of ALL types both on the front end and on your backend.

Collapse
 
indigo744 profile image
Guillaume

It's always nice to see a security conscious dev. This is good that you're looking out for potential XSS flaws.

However, I am sorry to say that you are still wrong.

First, you are conflating validation and sanitization. In this post, OP described a way to validate an email based on regexp. I said it was pointless, as validation by email confirmation is the only real way to do this. Sanitization was never really discussed.

But anyway, let's talk about sanitization and security.
You should not sanitize user input. Well, not really, at least not blindly because you may remove useful data without knowing.
Instead, you should validate input (in frontend and backend), and encode output.

Validating input simply checks that the user supplied data is what is expected (ex: a number in a range). This is not really related to security and is domain-dependant. It mainly avoid storing wrong values in the DB. It can help reduce XSS, but will not always protect against XSS because rules can always be bypassed. Do not rely only on validation for securing user input.

Encoding output is where the security against XSS lies. What it means is to use the proper encoding function targeting the output syntax. For a usual web page in HTML, it means encoding the HTML entities (or maybe even more, if you output inside a script tag...). For an API outputting XML, it means encoding the XML entities. And so on... The crux is that you MUST ALWAYS encode depending on the syntax you insert data in.

You may ask why not encoding the input before storing it in DB? Well, you never know where the data may be used...
Remember that not all app are web app. Some app may take user data from a website and store it in a DB, but may display it later in a desktop app written in Java. Hence, the data in your DB should not be already encoded.

It is also strongly recommended to encode any data coming from the DB, whether it is user supplied (name, email, ...) or not (internal values, ...) in the name of security in depth.

To be complete regarding XSS mitigation on web app specifically, you should not only encode output, you should also implement Content Security Policy (CSP). Expliciting trusted sources for scripts, stylesheets,... will greatly help in reducing the attack surface, should an untrusted user-supplied data slip through the encoding.

But I'm only scratching the surface. Don't take my word for it and please take the time to look into it yourself. Here are some links to get you started:

cheatsheetseries.owasp.org/cheatsh...

owasp.org/www-project-top-ten/

developer.mozilla.org/en-US/docs/W...

Take care.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Hi,

I get your point here, and i've also written about HTML/JS/Backend validation, but you must also realise implementing 2 factor auth on email is an option, but do you really want to, for us no, we will loose a lot of people who'm we only sending marketing mails?

In this case it's more about validating we don't get the occasional spammers who just keyboard bash and it's more an exercise of helping people not mistyping a dot for instance.

I'm fully aware this doesn't validate anything and perhaps the headline is a bit misleading, nevertheless these kinds of validation are used really often and people should learn these as well.