Skip to main content

Validation

The validation plugin provides a framework for validating attached files. For some useful validators, see the validation_helpers plugin.

plugin :validation

Usage

The Attacher.validate method is used to register a validation block, which is called on attachment:

class VideoUploader < Shrine
  Attacher.validate do
    if file.duration > 5*60*60
      errors << "duration must not be longer than 5 hours"
    end
  end
end
attacher.assign(file)
attacher.errors #=> ["duration must not be longer than 5 hours"]

The validation block is executed in context of a Shrine::Attacher instance:

class VideoUploader < Shrine
  Attacher.validate do
    self    #=> #<Shrine::Attacher>

    file    #=> #<Shrine::UploadedFile>
    record  #=> #<Movie>
    name    #=> :video
    context #=> { ... }
  end
end

Inheritance

If you're subclassing an uploader that has validations defined, you can call those validations via super():

class ApplicationUploader < Shrine
  Attacher.validate { validate_max_size 5.megabytes }
end
class ImageUploader < ApplicationUploader
  Attacher.validate do
    super() # empty parentheses are required
    validate_mime_type %w[image/jpeg image/png image/webp]
  end
end

Validation options

You can pass options to the validator via the :validate option:

attacher.assign(file, validate: { foo: "bar" })
class MyUploader < Shrine
  Attacher.validate do |**options|
    options #=> { foo: "bar" }
  end
end

You can also skip validation by passing validate: false:

attacher.assign(file, validate: false) # skips validation

Manual validation

You can also run validation manually via Attacher#validate:

attacher.set(uploaded_file) # doesn't trigger validation
attacher.validate           # runs validation