Skip to content

Instantly share code, notes, and snippets.

@monobasic
Created November 27, 2012 12:59
Show Gist options
  • Save monobasic/4154122 to your computer and use it in GitHub Desktop.
Save monobasic/4154122 to your computer and use it in GitHub Desktop.
Auto generate jQuery Validation Rules for all Elements of a Form
// ouput all available form field names to console (copy paste it from there for a standard validation rules config object)
$.fn.generateDefaultValidationRules = function() {
var allFields = [];
var validationRulesString = '';
var allInputs = donationform.find(':input');
allInputs.each(function(index, element) {
var fieldName = $(element).attr('name');
if (jQuery.inArray(fieldName, allFields) === -1 && $(element).attr('type') !== 'hidden' && fieldName !== undefined) {
allFields.push(fieldName);
validationRulesString += fieldName + ': \'required\',\r\n';
}
});
validationRulesString = validationRulesString.slice(0, -3); // remove last ',' and linebreak
console.log(validationRulesString);
}
$.fn.generateDefaultValidationRules();
// ------------------------------------------------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment