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. 🏆

Get UI & Product Engineering Insights for Rails Apps (and product updates!)

Published at . Have suggestions or improvements on this content? Do reach out.

UI components for Ruby on Rails apps

$ 129 one-time
payment

Get Access
  • One-time Payment

  • Access to the Entire Library

  • Built using ViewComponent

  • Designed with Tailwind CSS

  • Enhanced with Hotwire