Tuesday, May 3, 2011

Fully custom validation error message with Rails

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.

From stackoverflow
  • 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.

    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

    marcgg : The problem is that my field is called :song_rep_xyz (well, something complicated), which is not user friendly
    marcgg : I just edited the question to be clearer
    Yar : Nice, thanks for this!
  • I recommend installing the custom_err_msg plugin which lets you do stuff like:

    validates_presence_of :non_friendly_field_name, :message => "^Friendly field name is blank"
    
    marcgg : thanks! isn't there a way to do it without a plugin ?
  • Now, the accepted way to set the humanized names is to use locales.

    # config/locales/en.yml
    en:
      activerecord:
        attributes:
          user:
            email: "E-mail address"
    

0 comments:

Post a Comment