Dave
Dave

Reputation: 633

Simple_form - How to add field name to error messages?

I have tweaked the bootstrap wrapper so that now I display all inline errors as a block above the simple_form field.

The form is a registration Devise form, specifically from the rails-prelaunch-signup composer app. How can I include the name of the field in the error message?

At the moment I am getting "isn't valid" or "can't be blank", however I would like something like "Email can't be blank".

Upvotes: 1

Views: 1643

Answers (3)

SebastianCastro
SebastianCastro

Reputation: 11

To add the attribute name on every error message, you can use the full_error helper instead of the classic error helper

Directly in your form

<%= simple_form_for @user do |f| %>
  <%= f.label :username %>
  <%= f.input_field :username %>
  <%= f.full_error :username %>

  <%= f.submit 'Save' %>
<% end %>

Or in your custom wrappers

# config/initializers/simple_form.rb

SimpleForm.setup do |config|
  # ...

  config.wrappers :vertical_form do |b|
    # ...
    b.use :label
    b.use :input
    b.use :full_error
  end
end

Upvotes: 1

mrusa
mrusa

Reputation: 81

Simpleform refers to rails localization if no error message is set in the model. So, if you want to add the attributes name to each error message, you could add something like this in your locale-file:

en:
  errors:
    messages:
      blank: "%{attribute} can't be blank"
      invalid: "%{attribute} isn't valid" 

Where %{attribute} is the placeholder where the fields name will be inserted.

Upvotes: 4

Greg Olsen
Greg Olsen

Reputation: 1380

You can set the error message in the model:

validates :email, presence: { error_message: "Email can't be blank" }

Upvotes: 1

Related Questions