This article was originally published on Rails Designer.
This is a quick one! π€π¨
Rails is known for great defaults and conventions. But there's one feature that I disable in all my Rails apps.
That feature is field_with_errors
(coming from ActiveModelInstanceTag). If there are any form validation errors for a field, this method wraps it with a div.field_with_errors
. In turn you can write CSS like this to style it accordingly:
.field_with_errors input,
.field_with_errors textarea,
.field_with_errors select {
background-color: #ffcccc;
}
But the extra div, more often than not, messes up the flow of the (carefully) crafted HTML and thus breaks the layout.
More importantly I prefer to write my own components to highlight form validation errors as it allows me to style my field- and label-inputs exactly how I want.
Fortunately disabling the field_with_errors
div is easy!
Create a new initializer and add this:
# config/initializers/field_with_errors.rb
ActionView::Base.field_error_proc = proc do |html_tag, instance|
html_tag.html_safe
end
It customizes Rails' form field error handling by setting a proc that returns the original HTML tag unmodified and safe for HTML rendering.
All invalid form fields are now returned as-is, instead of being wrapped in the field_with_errors
div. π
Top comments (0)