Validate uploaded file in Ruby on Rails

File Validators gem adds file size and content type validations to ActiveModel. Any module that uses ActiveModel, for example ActiveRecord, can use these file validators.

Install:

gem install file_validators

or add to Gemfile

gem 'file_validators'

Using

class Profile
  include ActiveModel::Validations

  attr_accessor :avatar
  validates :avatar, file_size: { less_than_or_equal_to: 100.kilobytes },
                     file_content_type: { allow: ['image/jpeg', 'image/png'] } 
end
Advertisements