6

How can I stop Rails to change my code when validation isn't passed.

Every time rails wraps my field with

<div class='field_with_error'>...</div>

I can edit fields_with_error class

.fields_with_error{ display: inline }

which works, but it is hacky

berkes
  • 26,996
  • 27
  • 115
  • 206
fl00r
  • 82,987
  • 33
  • 217
  • 237

3 Answers3

7

Its fine. Use the CSS thing instead of doing this.

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance_tag|
  "<span class='field_error'>#{html_tag}</span>"
end

Which I feel is more hacky :)

Rishav Rastogi
  • 15,484
  • 3
  • 42
  • 47
  • it is more hacky, true :) But I hope that there is a simple solution, like just turn off rails to change my code – fl00r Mar 18 '11 at 16:31
  • How is rails "changing your code"? If rails is wrapping it, then you are using rails helpers. Don't use those helpers if you don't want it, or write your own form builder helpers. – DGM Mar 18 '11 at 18:59
  • Did not work for me, it just displayed it as text, then this ```config.action_view.field_error_proc = Proc.new { |html_tag, instance| html_tag } ``` worked for me. [link](https://stackoverflow.com/questions/5267998/rails-3-field-with-errors-wrapper-changes-the-page-appearance-how-to-avoid-t). Note. I am using rails 5 – amaugo somto Jul 16 '19 at 09:32
5

I use this in environment.rb. Even more hacky ;-)

#
# Fix annoying <div class="fieldsWithError"> wrapping after validation
# http://dev.rubyonrails.org/ticket/3587
#

ActionView::Base.field_error_proc = Proc.new { |html_tag, instance| 
  msg = instance.error_message 

  if html_tag =~ /<(input|textarea|select)[>]+class=/
    class_attribute = html_tag =~ /class=['"]/ 
    html_tag.insert(class_attribute + 7, "error ") 
  elsif html_tag =~ /<(input|textarea|select)/
    first_whitespace = html_tag =~ /\s/ 
    html_tag[first_whitespace] = " class='error' "
  end 

  html_tag
}
auralbee
  • 8,741
  • 4
  • 29
  • 36
-1

You can also use jQuery to do it. Still feel like a hack but its working.

$('.field_with_errors input').unwrap();
MathRivest
  • 9
  • 1
  • 4