Search code examples
ruby-on-railsrails-activestorageruby-on-rails-5.2

ActiveStorage File Attachment Validation


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

Solution

  • 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