Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom error message for valid numericality of in rails

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.

like image 303
Omnipresent Avatar asked Feb 04 '23 06:02

Omnipresent


1 Answers

The currently accepted answer works, but here's a data driven way to do it using Rails' i18n:

Adding allow_blank: true to validates_numericality_of will take care of the empty problem.

Then you can use i18n to automatically translate attribute names for you (docs here). For prod_price you'd just add this to en.yml:

en:
  activerecord:
    attributes:
      product:
        prod_price: "Product price"

Now for the must be a number part, we can use i18n again. From the docs:

Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes, and/or validations.

There's a handy table of those namespaces here, where you can see that the message for a numericality validataion is not_a_number.

So now we can add that to en.yml thus:

en:
  activerecord:
    errors:
      models:
        product:
          attributes:
            prod_price:
              not_a_number: "must be a number"

Now when the validation fails it'll concatenate the two, to give you: Product price must be a number.

like image 152
davetapley Avatar answered Feb 07 '23 12:02

davetapley