ActiveStorage File Attachment Validation

Tom Rossi picture Tom Rossi · Jan 8, 2018 · Viewed 23.4k times · Source

Is there a way to validate attachments with ActiveStorage? For example, if I want to validate the content type or the file size?

Something like Paperclip's approach would be great!

  validates_attachment_content_type :logo, content_type: /\Aimage\/.*\Z/
  validates_attachment_size :logo, less_than: 1.megabytes

Answer

Tom Rossi picture Tom Rossi · Jan 9, 2018

Well, it ain't pretty, but this may be necessary until they bake in some validation:

  validate :logo_validation

  def logo_validation
    if logo.attached?
      if logo.blob.byte_size > 1000000
        logo.purge
        errors[:base] << 'Too big'
      elsif !logo.blob.content_type.starts_with?('image/')
        logo.purge
        errors[:base] << 'Wrong format'
      end
    end
  end