Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

How to: Validate attachment file size

Rahul Jayaraman edited this page · 3 revisions
Clone this wiki locally

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

Grab a copy of the validator from 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 

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

# 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")

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

Something went wrong with that request. Please try again.