Skip to content

Show the error messages next to the related fields instead of on top of the form

Rodrigo Muino Tomonari requested to merge github/fork/n-studio/form_error into main

Created by: n-studio

Motivation / Background

The default scaffold in Rails displays all the form errors in a <div> on top of the form.

  <% if user.errors.any? %>
    <div style="color: red">
      <h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
        <% user.errors.each do |error| %>
          <li><%= error.full_message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

Which is not a common UX pattern on most websites.

It's way more usual to display the error messages right next to the field related to the error. IMO, it would be much nicer/more intuitive to have something like this instead:

<%= form_with(model: user) do |form| %>
  <div>
    <%= form.label :name, style: "display: block" %>
    <%= form.text_field :name %>
    <%= form.error :name, style: "color: red" %>
  </div>

  <div>
    <%= form.submit %>
  </div>
<% end %>

Detail

This Pull Request adds the method error to the form builder and updates the forms generated via scaffold.

Checklist

Before submitting the PR make sure the following are checked:

  • This Pull Request is related to one change. Changes that are unrelated should be opened in separate PRs.
  • Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: [Fix #issue-number]
  • Tests are added or updated if you fix a bug or add a feature.
  • CHANGELOG files are updated for the changed libraries if there is a behavior change or additional feature. Minor bug fixes and documentation changes should not be included.

Merge request reports