Validate e-mail with HTML5 input element

by Manuel Strehl

HTML

<div id="a"></div>
<input id="test" value="" placeholder="e-mail address">
<input type="button" value="validate" onclick="validate()">

CSS

#a {
  background: gray;
    width: 30px;
    height: 30px;
}

JavaScript

/*
 * validate an e-mail address by leveraging the HTML5
 * input element with type "email"
 */

function validate() {
  var input = document.createElement('input');
  input.type='email';
  input.value=document.getElementById('test').value;
    
  if (input.checkValidity()) {
    document.getElementById('a').style.background = 'green';
  } else {
    document.getElementById('a').style.background = 'red';
  }
    
  return false;
}