I whipped together this quick email validation script the other day. As far as validation scripts go, it is more basic than basic.
Here is the jQuery:
$('#inputID').bind('blur focus', function(event){
if(event.type === 'blur'){
//cache jquery objects
var $invalidEmailError = $('#invalidEmailError'),
$submitButton = $('#submitButton'),
$this = $(this);
var v = $this.val();
//trim spaces
v = v.replace(/^\s+|\s+$/g, "");
//check email against regex
if(v.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)){
$invalidEmailError.hide();
$submitButton.removeAttr('disabled').removeClass('disabled');
$this.addClass('email-good').removeClass('email-bad');
}
else{
$invalidEmailError.show();
$submitButton.attr('disabled','disabled').addClass('disabled');
$this.addClass('email-bad').removeClass('email-good');
}
//replace email with trimmed version
$this.val(v);
}
//remove status styles while editing
if(event.type === 'focus'){
$(this).removeClass('email-bad email-good');
}
});
…and the html:
<input id="inputID" type="text" placeholder="Please enter an email" />
<button id="submitButton" disabled="disabled" type="submit">
Send
</button>
<div id="invalidEmailError" style="display:none">
Please enter a valid email address
</div>
…and some base css:
input[type="text"]{
border:1px solid grey;
}
input[type="text"].email-bad{
border:1px solid red;
}
input[type="text"].email-good{
border:1px solid green;
}
There are some things to consider with the way the events behave. The email gets validated against the regex when the input blur event fires. This means that the user must either tab to the submit button or click the submit twice. A fix would be to validate on click of the submit, then submit if it passes validation.
If you are using Modernizr, I would recommend wrapping this validator in a conditional statement so any browser that supports html5 form validation gets the native functionality (be sure to include the appropriate attributes on the input). Perhaps this is something for a future post.
Demo: http://jsfiddle.net/McWatt/hNB8s/
Uses the following:
- Email regex: www.regular-expressions.info/email.html
- JS library: jQuery 1.6.4