skip to content

In a Rails form view, how do you show a model's validation errors both as a summary above the form and beside each field?

level: juniorimportance: should knowfreq 55%

answer

  1. the scaffold's _form partial
  2. errors.any? and errors.count
  3. error.full_message per item
  4. errors.full_messages_for(:email)
  5. field_id(:email, :error) for aria

basics

~10 s

Above the form, loop over the record's errors when errors.any? and print each error.full_message, as the scaffold's _form partial does. Beside a field, print errors.full_messages_for(:email), which holds only that attribute's messages.

solid answer

~40 s

Rails ships no error-message view helper; the scaffold's `_form.html.erb` writes the summary itself: `if volunteer.errors.any?`, a heading with `pluralize(volunteer.errors.count, "error")`, then `volunteer.errors.each { |error| ... error.full_message ... }` in a list. For inline messages, read the same object through the builder: `form.object.errors.full_messages_for(:email)` gives "Email is invalid", while `errors[:email]` gives the bare "is invalid" for text placed after a label. Give each message an id from `form.field_id(:email, :error)` and point the input at it with `aria: { describedby: ... }` so screen readers announce it. Errors on `:base` belong to no field, so only the summary shows them. A small partial or a custom form builder keeps the per-field markup in one place.

code

erb · 5 lines
erb
<%# app/views/shared/_field_errors.html.erb %>
<%# locals: (form:, attribute:) %>
<% form.object.errors.full_messages_for(attribute).each do |message| %>
  <p id="<%= form.field_id(attribute, :error) %>" class="field-error"><%= message %></p>
<% end %>

go deeper

for a junior

Recall the scaffold's errors.any? block with error.full_message, and that errors.full_messages_for(:email) gives one field's messages.

for a middle

Explain the difference between errors[:attr] and full_messages_for, how form.object reaches the record in a partial, and why :base errors only appear in the summary.

for a senior

Build one reusable error-field pattern with field_id and aria-describedby, and make sure summaries render inside the frame or partial that the 422 response replaces.

for a principal

Choose a single error-presentation convention for the app's forms, partial, builder or component, so accessibility and wording do not drift between teams.

## What Rails gives you and what it does not Active Model collects validation failures in `record.errors`. Action View's automatic part is the `field_with_errors` wrapper around fields whose attribute has errors. Everything else is template code you write: the guides state that Rails does not include view helpers for printing error messages. The scaffold generator writes a starting point into each `_form.html.erb`. ## The summary The generated partial, adapted to a volunteer sign-up: ```erb <% if volunteer.errors.any? %> <div id="error_explanation" role="alert"> <h2><%= pluralize(volunteer.errors.count, "error") %> prohibited this sign-up from being saved:</h2> <ul> <% volunteer.errors.each do |error| %> <li><%= error.full_message %></li> <% end %> </ul> </div> <% end %> ``` - `errors.any?` keeps the block out of a fresh form. - `errors.count` counts messages, not attributes; two failures on `email` count as two. - `error.full_message` prefixes the human attribute name, so `format` failing on `email` reads "Email is invalid". Messages on `:base` have no prefix. ## Messages beside each field Two lookups cover most designs: | Call | Returns for a bad email | Use | |---|---|---| | `errors.full_messages_for(:email)` | `["Email is invalid"]` | text that must stand alone | | `errors[:email]` | `["is invalid"]` | text placed right after the label | Inside the form block the record is `form.object`, so a partial can work with any builder: ```erb <%= form.label :email %> <%= form.email_field :email, aria: { describedby: (form.field_id(:email, :error) if form.object.errors.include?(:email)) } %> <% form.object.errors.full_messages_for(:email).each do |message| %> <p id="<%= form.field_id(:email, :error) %>" class="field-error"><%= message %></p> <% end %> ``` ## Accessibility details 1. **Link message and input.** `form.field_id(:email, :error)` returns `volunteer_email_error`, built from the same root as the input's id. The `aria-describedby` attribute on the input points at it, so assistive technology reads the message with the field. A `nil` value is skipped, so the attribute only appears when there is an error. 2. **Announce the summary.** `role="alert"` on the summary container makes screen readers announce it when the re-rendered page appears. 3. **Do not rely on colour.** The default red wrapper is decoration; the text message is what makes the error accessible. ## Keeping it in one place Repeating that markup for every field is error-prone. Common approaches: - a partial such as `shared/_field_errors.html.erb` that takes the builder and the attribute; - a method you add to your own `FormBuilder` subclass, for example `form.error_for(:email)`, configured through `builder:` or `default_form_builder` (that mechanism belongs to the form-targets leaf); - a component library's form field component. ## Order and wording - `errors.each` yields errors in the order they were added, which follows the order validations are declared in the model. - The wording, "Email is invalid", comes from the locale files; changing it is the translations leaf's subject, not the view's. - The scaffold's generated summary uses an inline `style="color: red"` container; most apps replace it with their own class and the `role` shown above. The same `_form` partial is rendered by both `new.html.erb` and `edit.html.erb`, so one summary serves create and update failures. ## Errors that have no field `errors.add(:base, "Sign-ups for this event are closed")` attaches to the record as a whole. No field matches `:base`, so only the summary loop shows it. The same applies to any attribute that has no input in this form, which is why a summary is worth keeping even when every field shows its own message. ## Interview summary Print a summary from `errors.each` and `full_message`, print per-field text from `full_messages_for` or `errors[attr]` through `form.object`, connect each message to its input with `field_id` and `aria-describedby`, and keep `:base` errors in the summary.

  • Why does the summary print error.full_message instead of error.message?
    `message` is the bare text, such as "is invalid", which makes no sense in a list detached from its field. `full_message` prefixes the human attribute name, giving "Email is invalid"; for `:base` errors it is just the message.
  • Where should the summary go when the form sits inside a Turbo Frame?
    Inside the frame, in the same partial as the form. The 422 response replaces only the frame's content, so a summary rendered elsewhere in the layout would not update.

  • Rails 8.1 ships a built-in helper that prints all of a record's error messages.
  • errors.count returns the number of invalid attributes, not messages.
  • errors[:email] returns full sentences such as Email is invalid.
  • An errors.add(:base, ...) message appears next to the first field automatically.
  • The red field_with_errors box alone makes the form's errors accessible.