• Rails 4: Add data-error attribute to form field instead of using wrapper

I wanted to have data-error on the form field instead of the standard rails error wrapper <div class="field_with_errors"></div>. With a data attribute we can do some much nicer handling of the form field.

You just need to create this initializer:

# e.g. config/initializers/form_field_data_error_attribute.rb
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  if html_tag =~ /<(input|label|textarea|select)/
    html_field = Nokogiri::HTML::DocumentFragment.parse(html_tag)
    html_field.children.each do |c|
      c['data-error'] = instance.error_message.uniq.join(', ')

Now fields with errors just have the data-error attribute. Super easy to work with, and setting up proper CSS and tooltip behavior.

The Author

Dan Schultzer is an active experienced entrepreneur, starting the Being Proactive groups, Dream Conception organization, among other things. You can find him at twitter

Like this post? More from Dan Schultzer

Comments? We would love to hear from you, write us at @dreamconception.