Adding custom message on model validation in rails 3

Hi, I am developing an application in rails 3.0

I have post Model class Post < ActiveRecord::Base   validates :name , :presence => true end

I have added the presence of validation on post name. It shows me error that "Name can't be blank"

I have to give the custom message for the user so I have written like as follows:-

class Post < ActiveRecord::Base   validates :name , :presence => true , :message=>"Post name can't be blank." end

But it is giving me error:- "Unknown validator: 'message'"

Can anyone tell me How to give the custom message in rails 3 model validations?

Thanks, Mike

I think differently: Why can’t you use JavaScript to check for a blank field?

Regards,

Hey, I don't want to use the javascript, as rails directly provides us validations then why should we write code.

Is there anyone know how to add custom message on model validation in rails 3.0.0

Thanks, Mike.

Hi,

try the following:

class Post < ActiveRecord::Base   validates :name , :presence => { :message=>"Post name can't be blank." } end

Maksim.

Please quote when replying.

Edmond Kachale wrote:

I think differently: Why can't you use JavaScript to check for a blank field?

No way! JavaScript validations should never be relied on -- it's too easy for the client to turn them off and bypass them, or to submit a crafted GET or POST request that bypasses the HTML form entirely. Validation *must* be done on the server side.

Regards,

--- Edmond

Best,

Hi, Your solution is working but the message is coming like this:-

"Name Post name can't be blank."

My model post.rb is:-

class Post < ActiveRecord::Base   validates :name , :presence => { :message=>"Post name can't be blank."}   validates :title, :presence => true, :length => { :minimum => 5 }    has_many :comments , :dependent => :destroy end

Hi, Your solution is working but the message is coming like this:-

What solution, from whom? You did not quote the previous message so no-one knows what you are talking about.

Colin

Yes. I am talking about the Maksim solution.

Hi,

it's the default error_message_on behavior. You can try to override it. Another solution could be to write your message without the attribute: just "can't be blank.", so you get "Name can't be blank".

Hope it helps you. Regards, Maksim.