Skip to content

Instantly share code, notes, and snippets.

@amycheng
Created October 18, 2013 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amycheng/7047599 to your computer and use it in GitHub Desktop.
Save amycheng/7047599 to your computer and use it in GitHub Desktop.
A jQuery plugin for form validation. Use for e-mail, message text fields, as well as check boxes and radio buttons.
/*General Purpose Form Validation*/
(function($) {
$.fn.validateForm = function() {
var $form = $(this),
$submit = $form.find('button[type="submit"]'),
$messages = $('.form-messages[data-target="'+$form.attr('id')+'"]'),
successMessage = $form.attr('data-message'),
$requiredFields = $form.find('[data-required="true"]'),
requiredNum = $form.find('[data-required="true"]').length,
$needsValidation = $form.find('[data-validate="true"]'),
submittedFields=0,
formIsValid=false;
return this.each(function() {
$needsValidation.add($requiredFields).each(function(){
if ($(this).is('fieldset.radio-button-group')||$(this).is('fieldset.checkbox-group')) {
// binding validation to .change() because blur doesn't work on radios or checkboxes
$(this).find('input').each(function(){
$(this).change(function(){
$(this).parents('fieldset').validateField();
});
});
}else{
//binding validation to .blur
$(this).blur(function(){
$(this).validateField();
});
}
});
$submit.click(function(e){
e.preventDefault();
//clear out any error messages
$messages.empty();
$requiredFields.each(function(){
var $_this = $(this),
isValid= $_this.attr('data-valid');
if (isValid!=="true") {
$_this.validateField();
}else{
//keep track of how many required fields are valid
submittedFields++;
}
});
if (submittedFields==requiredNum) {
formIsValid=true;
}
$needsValidation.each(function(){
var $_this = $(this),
isValid= $_this.attr('data-valid');
if ($_this.val().length>0) {
$_this.validateField();
if (isValid!=="true") {
// if non-required fields are filled out and NOT valid, it invalidates the entire form
formIsValid=false;
}
}
});
if (formIsValid===true) {
$messages.append('<p class="confirmed">'+successMessage+'</p>');
/*submission script here*/
}
});
});
};
}(jQuery));
(function($) {
$.fn.validateField = function() {
var $_this = $(this),
fieldName=$_this.attr('name'),
counts,
min = 1,
max = 1000,
validated = false,
value=$_this.val(),
$messages = $('.form-messages[data-target="'+$_this.parents('form').attr('id')+'"]'),
message=$_this.attr('data-message');
//if these attributes are defined, replace the defaults
if ($_this.attr('data-min')) {min = parseInt($_this.attr('data-min'));}
if ($_this.attr('data-max')) {max = parseInt($_this.attr('data-max'));}
if (!fieldName) {fieldName=$_this.attr("id");} //fieldsets won't have names, so use IDs, this is used for messages
return this.each(function() {
//begin validation form elements
$('.'+fieldName+'-message').remove();
if ($_this.is('fieldset.checkbox-group')===true) {
counts=$_this.find('input:checkbox:checked').length;
//check to see if the number of checkboxes fall within range defined by min and max
if (counts>min&&counts<=max) {
validated=true;
}
}
if ($_this.is('fieldset.radio-button-group')===true) {
counts=$_this.find('input:radio:checked').length;
if (counts==1) {
validated=true;
}
}
if ($_this.is('select')===true) {
if (value.length>0) {
validated=true;
}
}
if ($_this.is('input')===true) {
var type = $_this.attr('type');
if (type=="text") {
if (fieldName=="email") {
var pattern = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9\-]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/i;
var isEmail;
isEmail = pattern.test(value);
if (isEmail===true) {
validated=true;
}
}else{
if (value.length>0){
validated=true;
}
}
}
}
if ($_this.is('textarea')) {
if (value.length > min && value.length <= max ) {
validated=true;
}
}
//END validation form elements
//added error classes
if (validated===false) {
$messages.append('<p class="'+fieldName+'-message">'+message+'</p>');
if ($_this.is('fieldset')){
$_this.addClass('missing');
}else{
$_this.parent().addClass('missing');
}
$_this.removeAttr('data-valid');
}else{
$_this.removeClass('missing');
$_this.parent().removeClass('missing'); //for fieldsets
$_this.attr('data-valid','true');
}
});
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment