Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 553
user_1357 Avatar asked Oct 06 '11 06:10

user_1357


People also ask

How do I validate in Ruby on Rails?

This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".

What is Validator error?

Validations errors are errors when users do not respond to mandatory questions. A validation error occurs when you have validation/response checking turned on for one of the questions and the respondent fails to answer the question correctly (for numeric formatting , required response).


3 Answers

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)

like image 145
user_1357 Avatar answered Oct 18 '22 11:10

user_1357


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" }
like image 43
Mario Uher Avatar answered Oct 18 '22 09:10

Mario Uher


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.

like image 32
prasvin Avatar answered Oct 18 '22 10:10

prasvin