Shalafister
Shalafister

Reputation: 399

Rails Error Validations show below the Field

I would like to use the error messages of Rails next to its Fields. For instance;

I have a form to create new user;

<h1>Sign up</h1>

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user) do |f| %>
       <%= render 'shared/error_messages', object: f.object %>

      <%= f.label :name %>
      <%= f.text_field :name, class: 'form-control' %>

      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.label :password %>
      <%= f.password_field :password, class: 'form-control' %>

      <%= f.label :password_confirmation, "Confirmation" %>
      <%= f.password_field :password_confirmation, class: 'form-control' %>

      <%= f.submit "Create my account", class: "btn btn-primary" %>

    <% end %>
  </div>
</div>

And I use, _error_messages.html.erb partial as;

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>
    <ul>
    <% object.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

I know it just takes the error messages and show them as list. I think there should be a way to check for errors in the hash on each field. Just do not know how.

Thank you for your help!

Upvotes: 0

Views: 52

Answers (1)

bhanu
bhanu

Reputation: 2460

you can create a helper method which takes the current object and attribute names as arguments and generates necessary html to display error inline/next to the fields. like

def errors_for(object, field_name)
  if object.errors.any? && object.errors.messages[field_name]
    object.errors.messages[field_name].join(', ')
  end
end

then you can simply call this helper method from your form as

  <%= f.label :email %>
  <%= f.email_field :email, class: 'form-control' %>
  <%= errors_for(@user, :email) %>

Upvotes: 1

Related Questions