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:

[javascript]
$("#email-input").on(‘invalid’, function (e) {
// do stuff
});

[/javascript]

Or if you’re old school

[javascript]
document.getElementById(’email-input’).addEventListener(‘invalid’, function(e){
// do stuff
});
[/javascript]

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:

[javascript]
$("#email-input").on(‘invalid’, function (e) {
if (e.target.validity.typeMismatch) {
alert("enter a valid email address!");
}
});
[/javascript]

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

[javascript]
$("#email-input").on(‘invalid’, function (e) {
if (e.target.validity.typeMismatch) {
e.target.setCustomValidity("enter a valid email address!");
}
});
[/javascript]

Clever stuff, eh?