ruby-on-railsactiveadminformtastic

How can I get ActiveAdmin to perform input validation on it's forms on the client side?


I have a form for creating a new resource in ActiveAdmin. Two of my fields are integers (peak_count and off_peak_count).

If I enter a string in those fields, I will receive a stack trace of a database error because the entered fields are of the wrong type. How can I get ActiveAdmin to enforce the input types of the fields on the client side before attempting to input the data into the db?

Here is my form:

form do |f|
    f.inputs do
      if f.object.new_record?
        f.input :name
      else
        f.input :id, :input_html => {:disabled => true}
        f.input :name, :input_html => {:disabled => true}
      end
      f.input :peak_count
      f.input :off_peak_count
    end
    f.actions
  end

Solution

  • Active admin should already be making these inputs of type number but the browser won't prevent other characters from being input.

    Below is what I use. I include it globally in active admin by putting it in a file that is required in active_admin.js:

    Coffee script:

    $ ->
      $("input[type='number']").keydown (c) ->
        return false if c.shiftKey
        return false unless c.which in
          [8,9,13,37,38,39,40,45,46,48,
          49,50,51,52,53,54,55,56,57,96,97,98,
          99,100,101,102,103,104,105,110,
          173,189,190]
    

    If you are only using JS you can convert it here.

    I would still add server side validation though.