Do it like => validates :photos, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'], size: { less_than: 500.kilobytes }, limit: { min: 1, ma
Do it like => validates :photos, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'], size: { less_than: 500.kilobytes }, limit: { min: 1, ma
Active Storage Validations is a gem that allows you to add validations for Active Storage attributes.
This gem is doing it right for you! Just use validates :avatar, attached: true, content_type: 'image/png' and that's it!
Active Storage Validations work with Rails 7.0.1 onwards and Ruby 3.3 onwards. Add this line to your application's Gemfile:
gem 'active_storage_validations'And then execute:
$ bundleOnce you have installed the gem, I18n error messages will be added automatically to your app. See Internationalization (I18n) section for more details.
Optionally, to use the image metadata validators (dimension, aspect_ratio and processable_file), you will have to add one of the corresponding gems:
gem 'ruby-vips', '>= 2.1.0'
# Or
gem 'mini_magick', '>= 4.9.5'Plus, you have to be sure to have the corresponding command-line tool installed on your system (libvips for ruby-vips, or ImageMagick for mini_magick — both locally and in CI / production).
We recommend libvips (ruby-vips + config.active_storage.variant_processor = :vips) for these validators. Rails already defaults Active Storage variants to libvips (ActiveStorage::Variant), and our image processor benchmarks show cold metadata analysis is about 8× faster than MiniMagick/ImageMagick on the same machine and fixtures. Warm validations (cached asv_* metadata) are similar for both.
To use the video and audio metadata validators (dimension, aspect_ratio, processable_file, duration and with_audio), you will not need to add any gems. However you will need to have the ffmpeg command-line tool installed on your system (once again, be sure to have it installed both on your local and in your CI / production environments).
To use the pdf metadata validators (dimension, aspect_ratio, processable_file and pages), you will not need to add any gems. However you will need to have the poppler tool installed on your system (once again, be sure to have it installed both on your local and in your CI / production environments).
To use the spoofing_protection option with the content_type validator:
true / :file): the UNIX file command (usually preinstalled on UNIX systems):magika): the Google Magika CLI — install via brew install magika, their install script, cargo install --locked magika-cli, or pipx install magikaBoth backends are optional system tools (not Ruby gems). Prefer :magika when you can install the CLI — it is generally more accurate than file, especially on textual / ambiguous formats. Be sure to install Magika in CI / production if you enable :magika.
If you want some inspiration about how to add imagemagick, libvips, ffmpeg, poppler or magika to your docker image, you can check how we do it for the gem CI (https://github.com/igorkasyanchuk/active_storage_validations/blob/master/.github/workflows/main.yml)
Optional global settings can go in an initializer. Example template:
…The gem emits two ActiveSupport::Notifications events:
| Event | Payload | Emitted |
|---|---|---|
analyze.active_storage_validations |
analyzer, command, timeout, timed_out, duration |
Every time an analyzer command runs (i.e. on a cache miss) |
timeout.active_storage_validations |
analyzer, command, timeout |
Only when a command exceeds its deadline |
command_timeout bounds metadata analysis used by dimension, aspect_ratio, duration, with_audio, pages, processable_file, and content_type (with spoofing_protection). When a command times out, analysis fails closed and the validator adds its usual error (file_not_processable / media_metadata_missing / audio_missing / content-type errors) — there is no separate timeout error message.
The 10s default is enough for typical uploads. Raise it (or set nil) if you analyze very large videos/PDFs, especially on slow or network storage — otherwise those files can start failing validation after upgrade. See upgrade to 4.x.
Per-validator override (applies to the analysis triggered by that validator; the first analysis for a blob is cached):
validates :video, duration: { less_than: 5.minutes, timeout: 30.seconds }Notes:
command_timeout (or per-validator timeout:) to nil disables the deadlineidentify through the same killable command runner (MiniMagick is only used to build the argv)timeout.active_storage_validationsList of validators:
Proc usage
Every validator can use procs instead of values in all the validator examples:
class User (record) { record.admin? ? 100 : 10 } }
endPerformance optimization
Some validators rely on an expensive operation (metadata analysis and content type analysis). To mitigate the performance cost, the gem leverages the ActiveStorage::Blob.metadata method to store retrieved metadata. Therefore, once the file has been analyzed by our gem, the expensive analysis operation will not be triggered again for new validations.
As stated in the Rails documentation: "Blobs are intended to be immutable in so far as their reference to a specific file goes". We based our performance optimization on the same assumption, so if you do not follow it, the gem will not work as expected.
This also covers metadata the analyzer cannot extract from a given file (e.g. a duration validation on an image): the gem remembers that the value is unavailable, so the validation keeps failing with media_metadata_missing but the file is only analyzed once. Files that yield no metadata at all — missing command-line tool, timed out command, unreadable file — are not remembered and get analyzed again on the next validation.
Validates if the attachment is present.
The attached validator has no options.
Use it like this:
class User
%>
Explicit accept values are never overridden. You can also disable inference:
# Globally — see [Configuration](#configuration) for a full initializer template
ActiveStorageValidations.infer_file_field_accept = false
# Equivalent:
ActiveStorageValidations.configure { |config| config.infer_file_field_accept = false }Notes:
/\Aimage\/.*\z/ (or video / audio / etc.) are inferred, as image/*/\Aimage\/(png|gif)\z/) are skipped, since they cannot be reliably represented in acceptcontent_type options are skipped: they are not called while the form renders, because their result can depend on record state that is only set on submit, and a raising proc would break the whole view for what is merely a frontend hint. Backend validation is unchanged; pass a custom accept: on those fields if you want the picker filteredif: / unless:) are not evaluated: their content types are always included in accept, even when the condition would skip the validator for that record. Backend validation is unchanged; use infer_accept: false (or a custom accept:) if the picker must match the active conditionsIf you choose to use a content_type 'shorthand' (like png), note that it will be converted to a full content type using Marcel::MimeType.for under the hood. Therefore, you should check if the content_type is registered by Marcel::EXTENSIONS. On Marcel 2 (Rails 8.2+), historical aliases such as audio/x-aac are still valid options and resolve to their canonical type (audio/aac). If the type is not registered, you can register it by adding the following code to your config/initializers/mime_types.rb file:
Marcel::MimeType.extend "application/ino", extensions: %w(ino), parents: "text/plain" # Registering arduino INO filesBe sure to at least include one the extensions, parents or magic option, otherwise the content type will not be registered.
By default, the gem does not prevent content type spoofing. Enable it with spoofing_protection:
validates :avatar, content_type: { in: [:png, :jpeg], spoofing_protection: true } # => :file (UNIX file CLI)
validates :avatar, content_type: { in: [:png, :jpeg], spoofing_protection: :file } # explicit
validates :avatar, content_type: { in: [:png, :jpeg], spoofing_protection: :magika } # Google Magika CLIOverride binary paths with ActiveStorage.paths[:file] / ActiveStorage.paths[:magika] if needed.
What is content type spoofing?
File content type spoofing happens when an ill-intentioned user uploads a file which hides its true content type by faking its extension and its declared content type value. For example, a user may try to upload a .exe file (application/x-msdownload content type) dissimulated as a .jpg file (image/jpeg content type).
How do we prevent it?
Spoofing protection compares the declared Active Storage content type to a type detected by a sniffer CLI, then uses Marcel parent types so near-matches still pass:
:file (default) — UNIX file / libmagic, mostly magicNo open issues yet, or sync has not completed.