Last Updated: February 25, 2016
·
2.189K
· agis

Rails custom validator for Paperclip image dimensions

Put this in models/dimensions_validator:

class DimensionsValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path)
    width = options[:width]
    height = options[:height]

    record.errors[attribute] << "Width must be #{width}px" unless dimensions.width == width
    record.errors[attribute] << "Height must be #{height}px" unless dimensions.height == height
  end
end

Then in your model you can do:

validates :image, dimensions: { width: 250, height: 100 }

From http://agis.heroku.com/blog/2012/09/14/validating-paperclip-image-dimensions-in-rails/