How to disable Rails Form's `.field_with_errors`
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. 🏆
Want to read me more?
-
Better Inline Validation for Rails Forms (with ViewComponent or partials)
Rails has great features in place for form validations. But the UX can be improved. Provide immediate and contextual feedback by moving form validations closer to the input fields. -
Use Tailwind CSS with Your Rails Forms
Learn how to use Rails' FormBuilder API to easily use Tailwind CSS wih your Rails forms. -
Nested forms without `accepts_nested_attributes_for` in Rails
Build nested forms in Rails without accepts_nested_attributes_for. Use separate forms with auto-save and Turbo Streams for a simpler solution.
Over to you…
What did you like about this article? Learned something knew? Found something is missing or even broken? 🫣 Let me (and others) know!
Comments are powered by Chirp Form
{{comment}}