Fully custom validation error message with Rails

Ruby on-Rails

Ruby on-Rails Problem Overview


Using Rails I'm trying to get an error message like "The song field can't be empty" on save. Doing the following:

validates_presence_of :song_rep_xyz, :message => "can't be empty"

... only displays "Song Rep XYW can't be empty", which is not good because the title of the field is not user friendly. How can I change the title of the field itself ? I could change the actual name of the field in the database, but I have multiple "song" fields and I do need to have specific field names.

I don't want to hack around rails' validation process and I feel there should be a way of fixing that.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Now, the accepted way to set the humanized names and custom error messages is to use locales.

# config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        email: "E-mail address"
    errors:
      models:
        user:
          attributes:
            email:
              blank: "is required"

Now the humanized name and the presence validation message for the "email" attribute have been changed.

Validation messages can be set for a specific model+attribute, model, attribute, or globally.

Solution 2 - Ruby on-Rails

In your model:

validates_presence_of :address1, message: 'Put some address please' 

In your view

<% m.errors.each do |attr, msg|  %>
 <%= msg %>
<% end %>

If you do instead

<%= attr %> <%= msg %>

you get this error message with the attribute name

address1 Put some address please

if you want to get the error message for one single attribute

<%= @model.errors[:address1] %>

Solution 3 - Ruby on-Rails

Try this.

class User < ActiveRecord::Base
  validate do |user|
    user.errors.add_to_base("Country can't be blank") if user.country_iso.blank?
  end
end

I found this here.

Update for Rails 3 to 6:

validate do |user|
  user.errors.add(:base, "Country can't be blank") if user.country_iso.blank?
end

Here is another way to do it. What you do is define a human_attribute_name method on the model class. The method is passed the column name as a string and returns the string to use in validation messages.

class User < ActiveRecord::Base

  HUMANIZED_ATTRIBUTES = {
    :email => "E-mail address"
  }

  def self.human_attribute_name(attr)
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end

end

The above code is from here

Solution 4 - Ruby on-Rails

Yes, there's a way to do this without the plugin! But it is not as clean and elegant as using the mentioned plugin. Here it is.

Assuming it's Rails 3 (I don't know if it's different in previous versions),

keep this in your model:

validates_presence_of :song_rep_xyz, :message => "can't be empty"

and in the view, instead of leaving

@instance.errors.full_messages

as it would be when we use the scaffold generator, put:

@instance.errors.first[1]

And you will get just the message you specified in the model, without the attribute name.

Explanation:

#returns an hash of messages, one element foreach field error, in this particular case would be just one element in the hash:
@instance.errors  # => {:song_rep_xyz=>"can't be empty"}

#this returns the first element of the hash as an array like [:key,"value"]
@instance.errors.first # => [:song_rep_xyz, "can't be empty"]

#by doing the following, you are telling ruby to take just the second element of that array, which is the message.
@instance.errors.first[1]

So far we are just displaying only one message, always for the first error. If you wanna display all errors you can loop in the hash and show the values.

Hope that helped.

Solution 5 - Ruby on-Rails

Rails3 Code with fully localized messages:

In the model user.rb define the validation

validates :email, :presence => true

In config/locales/en.yml

en:  
  activerecord:
    models: 
      user: "Customer"
    attributes:
      user:
        email: "Email address"
    errors:
      models:
        user:
          attributes:
            email:
              blank: "cannot be empty"

Solution 6 - Ruby on-Rails

In the custom validation method use:

errors.add(:base, "Custom error message")

as add_to_base has been deprecated.

errors.add_to_base("Custom error message")

Solution 7 - Ruby on-Rails

Related to the accepted answer and another answer down the list:

I'm confirming that nanamkim's fork of custom-err-msg works with Rails 5, and with the locale setup.

You just need to start the locale message with a caret and it shouldn't display the attribute name in the message.

A model defined as:

class Item < ApplicationRecord
  validates :name, presence: true
end

with the following en.yml:

en:
  activerecord:
    errors:
      models:
        item:
          attributes:
            name:
              blank: "^You can't create an item without a name."

item.errors.full_messages will display:

You can't create an item without a name

instead of the usual Name You can't create an item without a name

Solution 8 - Ruby on-Rails

I recommend installing the custom_error_message gem (or as a plugin) originally written by David Easley

It lets you do stuff like:

validates_presence_of :non_friendly_field_name, :message => "^Friendly field name is blank"

Solution 9 - Ruby on-Rails

One solution might be to change the i18n default error format:

en:
  errors:
    format: "%{message}"

Default is format: %{attribute} %{message}

Solution 10 - Ruby on-Rails

Here is another way:

If you use this template:

<% if @thing.errors.any? %>
  <ul>
    <% @thing.errors.full_messages.each do |message| %>
      <li><%= message %></li>
    <% end %>
  </ul>
<% end %>

You can write you own custom message like this:

class Thing < ActiveRecord::Base
  
  validate :custom_validation_method_with_message

  def custom_validation_method_with_message
    if some_model_attribute.blank?
      errors.add(:_, "My custom message")
    end
  end

This way, because of the underscore, the full message becomes " My custom message", but the extra space in the beginning is unnoticeable. If you really don't want that extra space at the beginning just add the .lstrip method.

<% if @thing.errors.any? %>
  <ul>
    <% @thing.errors.full_messages.each do |message| %>
      <li><%= message.lstrip %></li>
    <% end %>
  </ul>
<% end %>

The String.lstrip method will get rid of the extra space created by ':_' and will leave any other error messages unchanged.

Or even better, use the first word of your custom message as the key:

  def custom_validation_method_with_message
    if some_model_attribute.blank?
      errors.add(:my, "custom message")
    end
  end

Now the full message will be "My custom message" with no extra space.

If you want the full message to start with a word capitalized like "URL can't be blank" it cannot be done. Instead try adding some other word as the key:

  def custom_validation_method_with_message
    if some_model_attribute.blank?
      errors.add(:the, "URL can't be blank")
    end
  end

Now the full message will be "The URL can't be blank"

Solution 11 - Ruby on-Rails

Just do it the normal way:

validates_presence_of :email, :message => "Email is required."

But display it like this instead

<% if @user.errors.any? %>
  <% @user.errors.messages.each do |message| %>
    <div class="message"><%= message.last.last.html_safe %></div>
  <% end %>
<% end %>

Returns

"Email is required."

The localization method is definitely the "proper" way to do this, but if you're doing a little, non-global project and want to just get going fast - this is definitely easier than file hopping.

I like it for the ability to put the field name somewhere other than the beginning of the string:

validates_uniqueness_of :email, :message => "There is already an account with that email."

Solution 12 - Ruby on-Rails

Here is my code that can be useful for you in case you still need it: My model:

validates :director, acceptance: {message: "^Please confirm that you are a director of the company."}, on: :create, if: :is_director?

Then I have created a helper to show messages:

module ErrorHelper
  def error_messages!
    return "" unless error_messages?
    messages = resource.errors.full_messages.map { |msg|
       if msg.present? && !msg.index("^").nil?
         content_tag(:p, msg.slice((msg.index("^")+1)..-1))
       else
         content_tag(:p, msg)
       end
    }.join

    html = <<-HTML
      <div class="general-error alert show">
        #{messages}
      </div>
    HTML

    html.html_safe
  end

  def error_messages?
    !resource.errors.empty?
  end
end

Solution 13 - Ruby on-Rails

If you want to list them all in a nice list but without using the cruddy non human friendly name, you can do this...

object.errors.each do |attr,message|
  puts "<li>"+message+"</li>"
end

Solution 14 - Ruby on-Rails

In your view

object.errors.each do |attr,msg|
  if msg.is_a? String
    if attr == :base
      content_tag :li, msg
    elsif msg[0] == "^"
      content_tag :li, msg[1..-1]
    else
      content_tag :li, "#{object.class.human_attribute_name(attr)} #{msg}"
    end
  end
end

When you want to override the error message without the attribute name, simply prepend the message with ^ like so:

validates :last_name,
  uniqueness: {
    scope: [:first_name, :course_id, :user_id],
    case_sensitive: false,
    message: "^This student has already been registered."
  }

Solution 15 - Ruby on-Rails

I tried following, worked for me :)

1 job.rb

class Job < ApplicationRecord
	validates :description, presence: true
	validates :title, 
			  :presence => true, 
			  :length => { :minimum => 5, :message => "Must be at least 5 characters"}
end

2 jobs_controller.rb

def create
	  @job = Job.create(job_params)
	  if @job.valid?
	  	redirect_to jobs_path
	  else
	  	render new_job_path
	  end	  
	end

3 _form.html.erb

<%= form_for @job do |f| %>
  <% if @job.errors.any? %>
    <h2>Errors</h2>
    <ul>
      <% @job.errors.full_messages.each do |message|%>
        <li><%= message %></li>
      <% end %>  
    </ul>
  <% end %>
  <div>
    <%= f.label :title %>
    <%= f.text_field :title %>
  </div>
  <div>
    <%= f.label :description %>
    <%= f.text_area :description, size: '60x6' %>

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

Solution 16 - Ruby on-Rails

> A unique approach I haven't seen anyone mention!

The only way I was able to get all the customisation I wanted was to use an after_validation callback to allow me to manipulate the error message.

  1. Allow the validation message to be created as normal, you don't need to try and change it in the validation helper.

  2. create an after_validation callback that will replace that validation message in the back-end before it gets to the view.

  3. In the after_validation method you can do anything you want with the validation message, just like a normal string! You can even use dynamic values and insert them into the validation message.


#this could be any validation
validates_presence_of :song_rep_xyz, :message => "whatever you want - who cares - we will replace you later"

after_validation :replace_validation_message

def replace_validation_message
    custom_value = #any value you would like
    errors.messages[:name_of_the_attribute] = ["^This is the replacement message where 
    you can now add your own dynamic values!!! #{custom_value}"]
end

The after_validation method will have far greater scope than the built in rails validation helper, so you will be able to access the object you are validating like you are trying to do with object.file_name. Which does not work in the validation helper where you are trying to call it.

Note: we use the ^ to get rid of the attribute name at the beginning of the validation as @Rystraum pointed out referencing this gem

Solution 17 - Ruby on-Rails

graywh's answer is the best if it actually locales different in displaying the field name. In the case of a dynamic field name (based on other fields to display), I would do something like this

<% object.errors.each do |attr, msg| %>
<li>
  <% case attr.to_sym %>
  <% when :song_rep_xyz %>
    <%= #display error how you want here %>
  <% else %>
    <%= object.errors.full_message(attr, msg) %>
  <% end %>
</li>
<% end %>

the full_message method on the else is what rails use inside of full_messages method, so it will give out the normal Rails errors for other cases (Rails 3.2 and up)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarcggView Question on Stackoverflow
Solution 1 - Ruby on-RailsgraywhView Answer on Stackoverflow
Solution 2 - Ruby on-RailsFedericoView Answer on Stackoverflow
Solution 3 - Ruby on-RailsMaulinView Answer on Stackoverflow
Solution 4 - Ruby on-RailsMarco AntonioView Answer on Stackoverflow
Solution 5 - Ruby on-RailsLukasView Answer on Stackoverflow
Solution 6 - Ruby on-Railsamit_saxenaView Answer on Stackoverflow
Solution 7 - Ruby on-RailsRystraumView Answer on Stackoverflow
Solution 8 - Ruby on-RailsRyan BiggView Answer on Stackoverflow
Solution 9 - Ruby on-Railscappie013View Answer on Stackoverflow
Solution 10 - Ruby on-RailsCruz NunezView Answer on Stackoverflow
Solution 11 - Ruby on-RailsbrittohalloranView Answer on Stackoverflow
Solution 12 - Ruby on-RailsOleksii DanylevskyiView Answer on Stackoverflow
Solution 13 - Ruby on-RailsadamView Answer on Stackoverflow
Solution 14 - Ruby on-RailsluckyrubyView Answer on Stackoverflow
Solution 15 - Ruby on-RailsAigulView Answer on Stackoverflow
Solution 16 - Ruby on-RailsSami BirnbaumView Answer on Stackoverflow
Solution 17 - Ruby on-RailsAn Nguyen DangView Answer on Stackoverflow