Search code examples
ruby-on-railsrails-activestorage

ActiveStorage: How to validate content of file?


I would like to read the content of a file that is to be uploaded in a custom validation. Is it possible?

So far, I've seen that it's possible to perform some validations on the file's metadata (extention, size...) but not on it's content. I've also seen this question that's a bit similar, even though I don't want to modify the file. I just want to read it in a custom validation.


Solution

  • It seems like you can access the file being uploaded and simply read it in the validation.

    For Example

    class User < ApplicationRecord
      has_one_attached :resume
      
      validate :resume_contents
    
      private 
        def resume_contents
          return unless record.send(attribute).attached? && !record.attachment_changes['resume'].blank?
          file = record.attachment_changes['resume'].attachable
          if file.is_a?(ActionDispatch::Http::UploadedFile) && file.read =~ /bad content/i
            errors.add(:resume, :invalid, message: 'cannot contain bad content')
          end
        end
    end
    

    For a more in depth implementation you could refer to the active_storage_validations gem: