user_1357
user_1357

Reputation: 7940

Ruby on Rails: How to customize validation error message?

I have a following code:

validates :name, :presence => true

Error message produced is "Name can't be blank" Instead of using the actual attribute name (in this case "name") I want to display message as "Registration name can't be blank". How do I overwrite the default message on the validations? I tried appending :message but it didn't work...

Thanks!

Upvotes: 7

Views: 12128

Answers (3)

prasvin
prasvin

Reputation: 3009

Its a little late now (after about 35 days) to answer this. So, sorry for this. But just wanted to share that I had used a gem, more than a few months back, for custom error messages.

This plugin allows you to omit the attribute name for specific messages. All you have to do is begin the message with a ‘^’ character.

I just checked it at https://github.com/nwise/custom_error_message & it has not been updated since march. So, i probably used it at the right time.

ps : Your answer for defining the custom keys in the yml file is more appropriate though.

Upvotes: 6

user_1357
user_1357

Reputation: 7940

In en.yml file define custom keys as:

activerecord: 
  attributes:
    model_name:
      attribute_name1: key1
      attribute_name2: key2
                 ......

This key will be used automatically when errors are generated.

Reference: http://edgeguides.rubyonrails.org/i18n.html#translations-for-active-record-models (5.1 Translations for Active Record Models)

Upvotes: 15

Mario Uher
Mario Uher

Reputation: 12397

This will do the trick:

validates :name, presence: { message: "Registration name can't be blank" }

or the old hash rocket syntax version:

validates :name, :presence => { :message => "Registration name can't be blank" }

Upvotes: 8

Related Questions