Search code examples
ruby-on-railsactiveadmin

Rails ActiveAdmin decimal validation with error message


I am creating a form for my admin page which goes like this:

form do |f|
 f.semantic_errors
 f.inputs "Basic Details" do
   f.input :number
   f.inputs "Tests", class: "input-group-box", id: "tests" do
     f.has_many :tests, allow_destroy: true, heading: "Tests" do |test|
        test.input :expense_one, input_html: { min: 0.0 }
        test.input :expense_two, input_html: { min: 0.0 }
        test.input :expense_three, input_html: { min: 0.0 }
        test.input :total_cost, input_html: {
                                              readonly: true,
                                              value: (
                                                test.object.expense_one.to_f +
                                                test.object.expense_two.to_f +
                                                test.object.expense_three.to_f
                                              ).to_f
                                            }
   end
 end
end

I have added the min: 0.0 but when i input wrong values inside the field like the -30, -20, etc, it does not let me create the object which i want to create but i want it to show errors like it shows for the other field's using the f.semantic_errors, for example the it shows the number can't be blank

Can i add some similar error like "expense_one" should be minimum 0?

Also the total_cost if there are no inputs added for expense_one, two and three it shows 0.0 would it be possible to default it to nil if there are no inputs added?


Solution

  • Semantic errors are tied with ActiveRecord validations. If you want a validation error of minimum value to pop up on your form as a semantic error you should put that validation into your model. Something like this should work:

    class YourCoolModel < ApplicationRecord
      # other code ...
      validates :funcy_attribute, numericality: { greater_than: 0 }
      # other code ...
    end
    

    Another way to solve this issue is to specify validation directly on the HTML input as you already did it - input_html: { min: 0.0 }. But there is one more thing to make it work in ActiveAdmin - you should add novalidate: false to your form definition since ActiveAdmin disables html validations by default.

      form html: { novalidate: false } do |f|
        f.input :funcy_attribute, as: :number, min: 0
      end
    

    HTML validation is different from ActiveRecord validation in that they are made on the client side (browser) and it looks differently in different browsers since these validations are native.

    I hope it will help you)