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).

html5_email_type_validation

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 (e.target.validity.typeMismatch) {
      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 (e.target.validity.typeMismatch) {
      e.target.setCustomValidity("enter a valid email address!");
    }
  });

Clever stuff, eh?