Misha Moroshko
Misha Moroshko

Reputation: 171321

Rails: How to set different ":message" for each one of the possible errors?

I use this validation:

validates_numericality_of :price, :greater_than_or_equal_to => 0, :less_than => 1000000

How could I set a different :message for each one of the following cases ?

Upvotes: 2

Views: 1024

Answers (4)

thefugal
thefugal

Reputation: 1214

Assuming you're using Rails 3, another option you have is to create a custom validator:

# You can put this in lib/better_numericality_validator.rb
class BetterNumericalityValidator < ActiveModel::EachValidator
    def validate_each(record,attribute,value)
        if value < 0
            record.errors[attribute] << "must be greater than or equal to 0"
        elsif value >= 1000000
            record.errors[attribute] << "must be less than 1000000")
        end
    end
end

Then you can use your custom validator in your model:

# In your model.rb
validates :price, :better_numericality => true

This method is very similar to Anubhaw's answer. But pulling the logic out into the a custom validator makes it so that you can reuse the validation elsewhere easily, you can easily unit test the validator in isolation, and I personally think that validates :price, :better_numericality => true leaves your model looking cleaner than the alternative.

Upvotes: 3

vonconrad
vonconrad

Reputation: 25377

At some point, you should probably ask yourself whether it isn't time to apply some convention over configuration.

In my opinion, an error message such as "Please enter a valid price greater than 0 and less than 1 million" (or similar) is a perfectly valid solution to the problem. It prevents you from adding unnecessary complexity to your application and allows you to move on to other (presumably more important) features.

Upvotes: 0

Zach Inglis
Zach Inglis

Reputation: 1257

How about:

validates_numericality_of :price, :greater_than_or_equal_to => 0, :message => "Foo"
validates_numericality_of :price, :less_than => 1000000, :message => "Bar"

I've not tested it, but it should work? Alternatively, Anubhaw's question is a good fallback.

Upvotes: 1

Anubhaw
Anubhaw

Reputation: 6068

You can use following in model.rb:-

def validate
  if self.price < 0
      errors.add(:price, "custom message")
  elsif self.price > 1000000
      errors.add(:price, "custom message")
  end
end

Thanks....

Upvotes: 3

Related Questions