HTML5 input type “email” validation

The HTML5 “email” input type is great for short-cutting the usual email validation javascript mess. Just by defining your input box as “type=’email'” you get validation for free (in modern browsers).


But how do you hook into this? Perhaps change the message or do some other actions at the same time? Check out the “invalid” event:

 $("#email-input").on('invalid', function (e) {
     // do stuff

Or if you’re old school

document.getElementById('email-input').addEventListener('invalid', function(e){
	// do stuff

This returns a ValidtyState object on which you have the following properties:

  • badInput
  • customError
  • patternMismatch
  • rangeOverflow
  • rangeUnderflow
  • stepMismatch
  • tooLong
  • typeMismatch
  • valid
  • valueMissing

So you can work with it like so:

 $("#email-input").on('invalid', function (e) {
    if ( {
      alert("enter a valid email address!");

Or you could even override the default message that appears in the tooltip:

 $("#email-input").on('invalid', function (e) {
    if ( {"enter a valid email address!");

Clever stuff, eh?

2 thoughts on “HTML5 input type “email” validation

Leave a Reply to Vlad Cancel reply

Your email address will not be published. Required fields are marked *