Created
July 14, 2009 16:40
-
-
Save jnunemaker/147052 to your computer and use it in GitHub Desktop.
jQuery and Rails form errors
This file contains 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
(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); |
This file contains 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
// 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