rails的错误提示field_with_errors


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

# File actionview/lib/action_view/helpers/active_model_helper.rb, line 28
def error_wrapping(html_tag)
  if object_has_errors?
    @template_object.instance_exec(html_tag, self, &Base.field_error_proc)
  else
    html_tag
  end
end

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 {
    border-color: var(--bs-form-invalid-border-color);
    padding-right: calc(1.5em + 0.75rem);
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx=    '6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right calc(0.375em + 0.1875rem) center;
    background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

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

阅读量: 644
发布于:
修改于: