Skip to content

Instantly share code, notes, and snippets.

@adamhunter
Forked from jnunemaker/errors.js
Created July 14, 2009 17:36
Show Gist options
  • Save adamhunter/147078 to your computer and use it in GitHub Desktop.
Save adamhunter/147078 to your computer and use it in GitHub Desktop.
(function($) {
// errors is an array of errors
// render :json => {:errors => @item.errors.full_messages}
function FormErrors(errors) {
var self = this,
error_count = errors.length;
this.html = function() {
var html = '';
html += '<div class="errorExplanation" id="errorExplanation">';
html += errorHeading();
html += errorUl();
html += '</div>';
return html;
}
function errorUl() {
var lis = $(errors).inject('', function(lis) {
lis += '<li>' + this + '</li>';
return lis;
});
return '<ul>' + lis + '</ul>';
}
function errorHeading() {
var error_str = error_count == 1 ? 'error' : 'errors';
return '<h2>' + error_count + ' ' + error_str +' prevented this form from being saved</h2>';
}
}
$.fn.removeErrors = function() {
return this.each(function() {
$(this).find('.errorExplanation').remove();
});
}
$.fn.showErrors = function(errors) {
return this.each(function() {
$(this).removeErrors().prepend(new FormErrors(errors).html());
});
}
})(jQuery);
// assumes that errors are output like rails with class of errorExplanation and that the errors are inside the form; to get the error array you can just render :json => @item.errors.full_messages when a thing is invalid
// this will remove the errors that exist and add the new errors to the form
$('#new_item').showErrors(["Title can't be blank", "Body is too long"]);
// this will remove any errors that exist in a form
$('#new_item').removeErrors()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment