jQuery: inline email validation
by gabrieleromanato
HTML
<form id="test" action="#" method="post">
<div>
<label for="email">E-mail</label>
<input type="text" name="email" id="email" />
</div>
</form>
CSS
form {
margin: 2em;
}
label {
display: block;
font-weight: bold;
margin-bottom: 0.4em;
}
#email {
width: 12em;
padding: 5px;
font-size: 1em;
background: #f5f5f5;
border: 1px solid #c0c0c0;
}
#email:focus {outline-style: none;}
JavaScript
var validateEmail = function(elementValue) {
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
$('#email').keyup(function() {
var value = $(this).val();
var valid = validateEmail(value);
if (!valid) {
$(this).css('color', 'red');
} else {
$(this).css('color', '#000');
}
});