Skip to content

Instantly share code, notes, and snippets.

@micah1701
Created April 5, 2016 06:06
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 micah1701/b701950fc676c2d946323959c6da6ff2 to your computer and use it in GitHub Desktop.
Save micah1701/b701950fc676c2d946323959c6da6ff2 to your computer and use it in GitHub Desktop.
Super simple script to enforce required fields in form. Just add a "required" attribute to the tag. If its blank, it adds some bootstrap error classes to the parent form-group container. Also validates e-mail fields.
var invalid_fields = 0; //global var can be accessed without calling function
function validate()
{
invalid_fields = 0; // reset counter
$("[required]").each(function(){
var val = $(this).val();
if(val == "" || val == null || val.match('/select/i'))
{
$(this).closest('.form-group').addClass('has-error has-danger');
invalid_fields++;
}
else
{
$(this).closest('.form-group').removeClass('has-error has-danger');
}
});
$("[type='email']").each(function(){
if( !/[a-z]+@[a-z]+\.[a-z]+/.test( $(this).val() ))
{
$(this).closest('.form-group').addClass('has-error has-danger');
invalid_fields++;
}
else
{
$(this).closest('.form-group').removeClass('has-error has-danger');
}
});
return invalid_fields;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment