Customize Field Errors with Rails 5 & Bootstrap 4

Categories: Coding, Solutions

Building a new app for one of my clients I had the need to customize Rails’ internal form error fields. By default Rails will add the “`field_with_errors“` class to an invalid input and call it a day. Unfortunately, if you’re using Bootstrap 4 (I’m using Beta) then you’re going to need to do a lot of customization in order for this to look right.

But, I hate trying to fight Bootstrap, so I set about trying to make Rails and Bootstrap play nice. I adapted this solution from rubyplus.org to work with the new Bootstrap 4 layouts. The gist is available on my github: Customize Field Errors with Rails 5 and Bootstrap.  It’s pretty simple, but here’s what you need to do.

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  html = ''

  form_fields = [
    'textarea',
    'input',
    'select'
  ]

  elements = Nokogiri::HTML::DocumentFragment.parse(html_tag).css "label, " + form_fields.join(', ')

  elements.each do |e|
    if e.node_name.eql? 'label'
      html = %(#{e}).html_safe
    elsif form_fields.include? e.node_name
      e['class'] += ' is-invalid'
      if instance.error_message.kind_of?(Array)
        html = %(#{e}<div class="invalid-feedback">#{instance.error_message.uniq.join(', ')}</div>).html_safe
      else
        html = %(#{e}<div class="invalid-feedback">#{instance.error_message}</div>).html_safe
      end
    end
  end
  html
end

Like I said, pretty simple but it makes things look a lot more snazzy.

What do you think? Comment here or on the gist to let me know what you think. Enjoy!

«
»