Skip to content

How to: Validate attachment file size

chrisbloom7 edited this page Jun 6, 2011 · 10 revisions

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.

Clone this wiki locally