Skip to content

Instantly share code, notes, and snippets.

@justinwhall
Created March 8, 2012 01:42
Show Gist options
  • Save justinwhall/1997916 to your computer and use it in GitHub Desktop.
Save justinwhall/1997916 to your computer and use it in GitHub Desktop.
jQuery: Form validator
jQuery(document).ready(function() {
jQuery('form#contactForm').submit(function() {
jQuery('form#contactForm .error').remove();
var hasError = false;
jQuery('.requiredField').each(function() {
if(jQuery.trim(jQuery(this).val()) == '') {
//var labelText = jQuery(this).prev('label').text();
jQuery(this).parent().append('<span class="error text-error">&larr; Required field</span>');
hasError = true;
}
else if(jQuery(this).hasClass('email')) {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(jQuery.trim(jQuery(this).val()))) {
//var labelText = jQuery(this).prev('label').text();
jQuery(this).parent().append('<span class="error text-error">&larr; Invalid Email.</span>');
hasError = true;
}
}
else if (jQuery(this).hasClass('captcha')){
if(jQuery.trim(jQuery(this).val()) != '10') {
jQuery(this).parent().append('<span class="error text-error">&larr; Are you a spammer?</span>');
hasError = true;
}
}
});
if(!hasError) {
jQuery('#thankyou').append('<img id="contact-loader" src="http://www.justinwhall.com/wp-content/themes/justinwhall/images/loader.gif" alt="Loading&hellip;" height="41" width="41" />');
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
jQuery('form#contactForm').slideUp("fast", function() {
jQuery(this).before('<div class="opacity-wrap thanks-wrap"><p class="thanks"><strong>Thanks!</strong> Your form was submitted successfully. I check my email frequently, so expect to hear from me shortly.</p></div>');
jQuery('#contact-loader').fadeOut('slow');
});
});
}
return false;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment