January 16, 2014

Show form errors next to the form fields

Ruby on Rails doesn't show form errors next to the form fields out of the box. But this behaviour can be implemented with few lines of code.

As fisrt create new form helper.

# app/helpers/form_helper.rb
module FormHelper
  def errors_for(field, form_object)
    if form_object.errors.messages[field]
      form_object.errors.messages[field].map do |error|
        "<span class=\"field-error\">#{form_object.class.human_attribute_name(field)} #{error}</span><br />"
      end.join("\n").html_safe
    end
  end
end

And the use it in your form viewes.

<%= f.password_field :password, autocomplete: :off %>
<%= errors_for(:password, f.object) %>

Above code will show all related erros for :password in your views.

I believe that this behaviour is provided by some gems, for example simple_for, but you can use my solution if you do not want to have additional functionality.

Hey there!

My name is Patrik Bóna and I am the only programmer at Memberful. This blog is kind of dead, but I just started my own Ruby on Rails screencast. Follow me on Twitter if you want to be notified about my newest videos.