Created
March 8, 2012 01:42
-
-
Save justinwhall/1997916 to your computer and use it in GitHub Desktop.
jQuery: Form validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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">← 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">← 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">← 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…" 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