Created
April 5, 2016 06:06
-
-
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.
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
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