Skip to content

Instantly share code, notes, and snippets.

@denniscastro
Forked from jnunemaker/errors.js
Created November 29, 2011 04: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 denniscastro/1403386 to your computer and use it in GitHub Desktop.
Save denniscastro/1403386 to your computer and use it in GitHub Desktop.
jQuery and Rails form errors
(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