HTML5 Email Validation | skybert.net

HTML5 Email Validation


Before the advent of HTML5, you would have to write a beefy function in JavaScript or load a 3rd party library to get proper validation of user entered values, like for instances, email addresses.

HTML5 solves this by providing more legal values for the type attribute of the <input/> element. The browser uses this to give a consistent user interface and validation for all input fields. However, with the email input type there's a caveat that most people are not aware of and which will potentially leave your system with lots of unusable email addresses.

HTML5 makes input validation easy

Most people and frameworks, use <input type="email"/> and live happily ever after:

<input type="email"/>

HTML5 compatible browsers, like Mozilla Firefox and Google Chrome will aid the user in entering a valid address:

html5 input email

However, it isn't as straightforward as you might think

However, this is not sufficient for all practical use cases, as this will not catch errors like the user entering john@gmail instead of john@gmail.com. This is because that email, by specification, doesn't require a top level domain as this is a perfectly valid email when you're on a local network.

html5 input email

The thing, though, is that in real life, we all have to deal with users entering "real" email addresses to the likes of gmail.com, hotmail.com and yahoo.com, i.e. john@gmail.com.

The road less travelled by

To accomplish this, we have to extend our input field declaration to something like this:

<input
  type="email"
  pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,63}$"
/>

Now, the browser will guide the user to a successful email entry, including the top level domain (e.g. .com):

html5 input email

With the pattern we applied above, the user is requested to enter at least two characters after the dot, which should fit most use cases:

html5 input email

Conclusion

As always, when you know the caveats, it's easy. Still, most people get this one wrong, so be sure to include the pattern in the input field so that you're sure the data quality in your system is as high as possible.

Cheers!

Footnotes

Server side validation

As always, you should never trust anything coming from the client, so email validation on the server side is in order no matter how great the HTML or JS is.

Non-HTML5 browsers

If you're supporting non-HTML5 browsers, you may still want to fall back to a JS library for email validation


Licensed under CC BY Creative Commons License ~ gmail torstein.k.johansen @ gmail ~ twitter @torsteinkrause ~