user4932805
user4932805

Reputation:

Customize Form Error Messages in Rails

So, I'm trying to come up with a way to customize the error messages in form_for's. The most elegant way to do this, in my opinion, would be inside the text area itself. So far, any method I've tried messes up the form completely. Please share your thoughts and methods. Simple form:

 <%= f.label :name, 'Name' %><br> 
 <%= f.text_field :name, size: 30 %>

 <%= f.label :password, 'Password' %><br>
 <%= f.password_field :password, size: 30 %>

<%= f.label :password_confirmation, 'Confirm' %><br>
<%= f.password_field :password_confirmation, size: 30 %>

<%= f.submit %>

As you can see, no errors mentioned here since I've added an initializer as follows:

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
errors = Array(instance.error_message).join(',')

if html_tag =~ /^<label/
    html_tag
    else
    %(#{html_tag}<span class="validation-error">&nbsp;#{errors}</span>).html_safe
end
end

Upvotes: 0

Views: 1378

Answers (4)

Pascal
Pascal

Reputation: 1178

My version of the common solution:

The helper method:

def errors_for(model, attribute)
  if model.errors[attribute].any?
    content_tag :span, class: 'error' do
      attribute.to_s.humanize + " " + model.errors[attribute].to_sentence
    end
  end
end

The view:

<%= errors_for @user, :name %>

What you get:

"Name can't be blank and is too short (minimum is 2 characters)"

Upvotes: 1

usmanali
usmanali

Reputation: 2036

Still a better can be using full_messages_for:

In you helper define:

def error_message_for(record, field)
  record.full_messages_for(field).join(",")
end  

If you do not want to show full message, you can use:

  record.errors.get(field).join(",")

And then in your view:

<%= errors_message_for @lesson, :description %>

Upvotes: 0

Adnan Devops
Adnan Devops

Reputation: 503

Another way of showing error messages:

    def error_messages_for object
      error_content = ''
      if object.errors.any?
       error_content += content_tag(:div, :id => 'error_explanation',  :class => 'alert alert-error') do
        content_tag(:h3, "#{pluralize(object.errors.count, "error")} prohibited this #{object.class.name.downcase} from being saved:") +
        content_tag(:ul, class: 'unstyled') do
          object.errors.full_messages.each do |message|
            concat content_tag(:li, "#{message}") if message.present?
          end
        end
      end
    end
    error_content.html_safe
  end
    Inside views use this helper:
    <%= error_messages_for @sample %>

Upvotes: 0

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

Use a helper method

def errors_for(model, attribute)
  if model.errors[attribute].present?
    content_tag :span, :class => 'error_explanation' do
      model.errors[attribute].join(", ")
    end
  end
end

And in view:

  <%= lesson_form.text_field :description %><br />
  <%= errors_for @lesson, :description %>    

Upvotes: 0

Related Questions