Harsha M V
Harsha M V

Reputation: 54949

Rails Display Form Error Below Each Field

I have the following form

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
      <% @user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <%= @user.errors.messages[:name] %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :email %><br>
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :password %><br>
    <%= f.password_field :password %>
  </div>
  <div class="field">
    <%= f.label :phone %><br>
    <%= f.text_field :phone %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

I want to display form error for each field below it instead of everything on the top. Went through rails guide but was not able to figure how to do it.

Upvotes: 8

Views: 5778

Answers (1)

Himesh
Himesh

Reputation: 646

You can write a helper to return error message for any field of any object

In /app/helpers/application_helper.rb:

def show_errors(object, field_name)
  if object.errors.any?
    if !object.errors.messages[field_name].blank?
      object.errors.messages[field_name].join(", ")
    end
  end
end 

In view file:

<div class="field">
  <%= f.label :name %><br>
  <%= f.text_field :name %>
  <p class='error'><%= show_errors(@user, :name) %></p>
</div>

Upvotes: 15

Related Questions