custom error message for valid numericality of in rails
ruby-on-rails, validation
Solution
You can have custom messages without writing your own validate method. Just add `:message`:
`validates_presence_of :prod_price, :message => "Product price can't be blank"`
If you want to skip the numericality validation when `prod_price` is not present, add :allow_nil:
`validates_presence_of :prod_price, :message => "Product price can't be blank"` `validates_numericality_of :prod_price, :allow_nil => true`
Then the numericality check will not run when `prod_price` is missing.
EDIT:
Wait, you don't want the field name to show up in the error message, do you? I missed that. So you'll need the custom validation after all.
EDIT #2:
Ok how about this then:
protected
def validate
if prod_price.blank?
errors.add "Product price can't be blank"
else
begin
Integer(attributes_before_type_cast["prod_price"])
rescue ArgumentError
errors.add "Product price must be a number"
end
end
end
Problem
I wanted to have custom error messages for my field names. I stumbled upon another SO question So I added something like this: ``` class Product < ActiveRecord::Base validate do |prod| prod.errors.add_to_base("Product price can't be blank") if prod.prod_price.blank? end end ``` But I also want to check the numericality of prod_price. If I just add `validate_numericality_of :prod_price` and product price is empty then both the error messages show up (empty and is not a number). How can I just have 'is not a number' error message show up only when product price is NOT empty? I tried doing ``` class Product < ActiveRecord::Base validate do |prod| prod.errors.add_to_base("Product price can't be blank") if prod.prod_price.blank? if !prod.prod_price.blank? prod.errors.add_to_base("Product price must be a number") if prod.prod_price.<whatdo i put here> end end end ``` Also, How can I have a custom message for 'is not a number'. I want to hide showing my column name to the user.