136

Email field:

<label for="job_client_email">Email: </label> 
<input type="email" name="job[client_email]" id="job_client_email">

looks like this:

without_error

But, if the email validation fails, it becomes:

<div class="field_with_errors">
  <label for="job_client_email">Email: </label>
</div> 
<div class="field_with_errors">
  <input type="email" value="wrong email" name="job[client_email]" id="job_client_email">
</div>

which looks like this:

with_error

How could I avoid this appearance change ?

1
  • Hi @misha-moroshko, I try do add the error class at the parent level as described here. I tried to dive into the rails code using byebug but I was lost immediately.. I wanted to setup this behavior in a little smart way by checking if those field have a parent..
    – SanjiBukai
    Jul 14, 2017 at 6:15

16 Answers 16

242

You should override ActionView::Base.field_error_proc. It's currently defined as this within ActionView::Base:

 @@field_error_proc = Proc.new{ |html_tag, instance| 
   "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe
 }

You can override it by putting this in your application's class inside config/application.rb:

config.action_view.field_error_proc = Proc.new { |html_tag, instance| 
  html_tag
}

Restart rails server for this change to take effect.

7
  • 4
    One little question: Why both the label and the input are wrapped ? How Rails decide what to wrap ? Mar 11, 2011 at 2:03
  • 4
    This is probably done so that you can style the label of a field with errors as well. Also, rails knows what to wrap because you tell it which fields belong to what attribute of the resource your are making the form for: f.label :password and f.password_field :password in the @resource.errors there would be a [:password] error set.
    – Mosselman
    Mar 21, 2012 at 16:16
  • 3
    If you're working with twitter bootstrap, or you want another example of what you can do in field_error_proc, checke out this awesome gist: gist.github.com/1464315
    – Ryan
    Jun 26, 2012 at 19:09
  • 2
    Why would one do "#{html_tag}".html_safe , and not html_tag.html_safe ?
    – Anurag
    Sep 16, 2013 at 11:26
  • 3
    Anurag: if html_tag happens to be nil, or anything other than a string, then a plain html_tag.html_safe would rais an error. Putting it in "#{html_tag}" implicitly calls html_tag.to_s, which hopefully will return a string, which will then be able to respond to html_safe
    – sockmonk
    Nov 4, 2013 at 21:52
103

The visual difference you are seeing is happening because the div element is a block element. Add this style to your CSS file to make it behave like an inline element:

.field_with_errors { display: inline; }
3
  • 2
    This is a hack at best because it negates whatever display: property being used (and other layout styles) on the html_tag.
    – rxgx
    May 4, 2012 at 21:34
  • 2
    I don't see it as a hack. The display property being used before this css is added is block which is causing the visual difference that is not desired. It doesn't negate any other layout styles on the tag. However, Ryan Bigg's answer is perfect if you want to change/remove the tag that wraps the field with errors.
    – dontangg
    May 7, 2012 at 12:46
  • I tried this, however, if your fields are inside if <p> tags, it does not seem to work (at least not on Firefox) since a <div> within a <p> breaks lines no matter what. Using Biggs solution, only replacing <div with <span seems to do the trick.
    – jpw
    Sep 18, 2012 at 4:29
75

I currently use this solution, placed in an initializer:

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  class_attr_index = html_tag.index 'class="'

  if class_attr_index
    html_tag.insert class_attr_index+7, 'error '
  else
    html_tag.insert html_tag.index('>'), ' class="error"'
  end
end

This allows me to merely add a class name to the appropriate tag, without creating additional elements.

8
  • 2
    This is awesome for using the error fields in an unobtrusive way.
    – rxgx
    May 4, 2012 at 21:33
  • 1
    Works on Rails 4.0.3. Mar 7, 2014 at 6:39
  • 1
    Worked for me. Had to restart rails server to notice changes though :) Apr 29, 2014 at 18:35
  • 1
    I loved this solution, but it won't work if you have other tag inside the label. Mar 28, 2016 at 15:47
  • Hi @Phobetron, indeed this is a nice solution. I search a way to add that class at the parent level instead like described here. I dove into the rails code but I lost myself immediately not being able to follow the rendering process with byebug.. Do you thing this is actually possible?
    – SanjiBukai
    Jul 14, 2017 at 6:12
22

The extra code is being added by ActionView::Base.field_error_proc. If you're not using field_with_errors to style your form, you can override it in application.rb:

config.action_view.field_error_proc = Proc.new { |html_tag, instance| html_tag.html_safe }

Alternatively, you can change it to something that suits your UI:

config.action_view.field_error_proc = Proc.new { |html_tag, instance| "<span class='field_with_errors'>#{html_tag}</span>".html_safe }
1
  • This is working well for me; seems to be the most elegant solution for use with Twitter Bootstrap
    – Avishai
    Mar 8, 2013 at 22:18
5

I am working with Rails 5 and Materialize-Sass and I am getting some issues with the default behavior from Rails to treat failed field validations as in the image below and it was because of the extra div added to the input fields where validation failed.

enter image description here

Working with @Phobetron answer and modifying Hugo Demiglio's answer too. I made some adjustments to those blocks of code and I get something working well in the following cases:

  • If both input and label has their own class attribute anywhere
    • <input type="my-field" class="control">
    • <label class="active" for="...">My field</label>
  • If the input or label tags does not have a class attribute
    • <input type="my-field">
    • <label for="...">My field</label>
  • if the label tag has another tag inside with the class attribute
    • <label for="..."><i class="icon-name"></i>My field</label>

In all those cases the error class will be added to the existing classes in the class attribute if exist or it will be created if it is not present in the label or input tags.

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
    class_attr_index = html_tag.index('class="')
    first_tag_end_index = html_tag.index('>')

    # Just to inspect variables in the console
    puts '😎 ' * 50
    pp(html_tag)
    pp(class_attr_index)
    pp(first_tag_end_index)

    if class_attr_index.nil? || class_attr_index > first_tag_end_index
        html_tag.insert(first_tag_end_index, ' class="error"')
    else
        html_tag.insert(class_attr_index + 7, 'error ')
    end

    # Just to see resulting tag in the console
    pp(html_tag)
end

I hope it could be useful for someone with the same conditions like me.

4

In addition of @phobetron answer, which doesn't work when you have other tag with class attribute, like <label for="..."><i class="icon my-icon"></i>My field</label>.

I did some changes on his solution:

# config/initializers/field_with_error.rb

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  class_attr_index = html_tag.index('class="')
  first_tag_end_index = html_tag.index('>')

  if class_attr_index.nil? || first_tag_end_index > class_attr_index
    html_tag.insert(class_attr_index + 7, 'error ')
  else
    html_tag.insert(first_tag_end_index, ' class="error"')
  end
end
1
  • But this will not work if your field does not have a class attribute
    – mzrnsh
    Oct 16, 2016 at 17:12
2

If for some reason you are still working on Rails 2 (like I am) check out the SO post here.

It offers a script to put in initializers.

2

One thing to keep in mind (as I discovered working through this today) is that if you float either the label or input fields (I'm floating all of the input fields right), the css will break even if you override ActionView::Base.field_error_proc.

An alternative is to drop a level deeper in the CSS formatting like so:

.field_with_errors label {
  padding: 2px;
  background-color: red;
}

.field_with_errors input[type="text"] {
  padding: 3px 2px;
  border: 2px solid red;
}
2

I made an option to disable this terrible thing for some objects

# config/initializers/field_error_proc.rb

module ActiveModel::Conversion
  attr_accessor :skip_field_error_wrapper
end

ActionView::Base.field_error_proc = Proc.new {|html_tag, instance|
  if instance.object && instance.object.skip_field_error_wrapper
    html_tag.html_safe
  else
    "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe
  end
}

So can use it like this:

@user.skip_field_error_wrapper = true
form_for(@user) do |f|
  ...
end
1

This is my solution building on top of @Phobetron's answer. Placing this code in application.rb, your <p> and <span> tags generated by the corresponding form.error :p calls will receive the fields_with_errors css tag. The rest will receive the error CSS class.

config.action_view.field_error_proc = Proc.new { |html_tag, instance|
  class_attr_index = html_tag.index 'class="'

  if class_attr_index
    # target only p's and span's with class error already there
    error_class = if html_tag =~ /^<(p|span).*error/
      'field_with_errors '
    else
      'error '
    end

    html_tag.insert class_attr_index + 7, error_class
  else
    html_tag.insert html_tag.index('>'), ' class="error"'
  end
}

I found this way the most flexible and unobstrusive of all previous to style the response across my forms.

1

If it's just for styling purposes (you don't mind the div), you can just add this to your css:

div.field_with_errors {
 display: inline;
}

The div will act like a span and it won't interfere with your design (since div is a block element – display: block;– by default, it will cause a new line after it closes; span is inline, so it does not).

1

If you just want to turn off errors for certain elements, e.g. checkboxes, you can do this:

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  doc = Nokogiri::HTML::Document.parse(html_tag)
  if doc.xpath("//*[@type='checkbox']").any?
    html_tag
  else
    "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe
  end
end
0

If its only about styling issues, we can overwrite "field_with_errors". But as that might effect other forms in our application, it's better to overwrite the "field_with_errors" class with in that form only.

Considering 'parent_class' is one of the parent class for form's error field (either form's class or class of any of the parent element for error field), then

  .parent_class .field_with_errors {
    display: inline;
  }

It will fix the issue as well as, it won't disturb any other forms in our applicaiton as well.

OR

If we need to override the style of "field_with_errors" for whole applicaiton, then as @dontangg said,

.field_with_errors { display: inline; } 

will do the fix. Hope it helps :)

0

If you don't want to change field_error_proc for your entire application, jQuery's unwrap can provide a more targeted solution for specific problem areas, e.g.,

$('FORM .field_with_errors > INPUT[type="checkbox"]').unwrap();
0

You can easily disable the extra <div class="field_with_errors"> div completely if you don't want it at all for particular form elements. E.g. if you don't want it for <label>'s, use a custom FormBuilder.

E.g:

class MyFormBuilder < ActionView::Helpers::FormBuilder
  # Strip the containing div for labels associated with invalid fields:
  def label(method, text = nil, options = {}, &block)
    super(method, text, options, &block).gsub(%r{<div.*?>|<\/div>}, '').html_safe
  end
end

and then either add , builder: MyFormBuilder to your form_with/form_for in the view, OR add default_form_builder MyFormBuilder to your controller (or base controller if you want it global behaviour).

You could do similarly for inputs and other form elements too.

Credit to Jack Casey for this answer.

0

To skip field_with_errors block use display: contents; on it

.field_with_errors { display: contents; }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.