Skip to content

How to: Validate image file size

Topher Hunt edited this page Aug 20, 2020 · 3 revisions

CarrierWave supports this since version 1.0.0.beta (2016-09-08) by defining a size_range method inside your uploader class. The method should return a Range for minimum/maximum allowed file size in bytes. For example, to allow a size of greater than or equal to 1 byte and less than or equal to 10 MB, you'd do:

def size_range
  1.byte..10.megabytes
end

Note that error messages are displayed in bytes. Also, the validation runs not only for the uploaded image, but for all versions as well (most probably a bug).

Implementation PR: https://github.com/carrierwaveuploader/carrierwave/pull/1026


You can use a pre-made ActiveModel validator such as the one provided by the file_validators gem. First, add the gem to your Gemfile.

Then, add the validation rule to your model (not your Uploader class), like this (see the documentation for more options):

  validates :avatar, file_size: { less_than: 2.gigabytes }

You can use a Rails custom validator to verify your attachment meets specific file size requirements.

Grab a copy of the validator from https://gist.github.com/1009861 and save it to your lib/ folder as file_size_validator.rb. Add the error translations to config/locales/en.yml or wherever is appropriate for your setup. Then do this in your parent model:

# app/models/brand.rb 
require 'file_size_validator' 
class Brand < ActiveRecord::Base 
  mount_uploader :logo, BrandLogoUploader 
  validates :logo, 
    :presence => true, 
    :file_size => { 
      :maximum => 0.5.megabytes.to_i 
    } 
end 

Like validates_length_of, validates_file_size accepts :maximum, :minimum, :in [range], and :is options.


A custom validator could also be used like this.

# app/models/user.rb 
class User< ActiveRecord::Base 
  attr_accessible :product_upload_limit
  has_many :products
end

# app/models/brand.rb 
class Product < ActiveRecord::Base 
  mount_uploader :file, FileUploader
  belongs_to :user
  validate :file_size

  def file_size
    if file.file.size.to_f/(1000*1000) > user.product_upload_limit.to_f
      errors.add(:file, "You cannot upload a file greater than #{upload_limit.to_f}MB")
    end
  end
 end

Here, the upload limit varies from user to user & is saved in the user model.

Clone this wiki locally