I would like to test that a required parameter with a custom type (File) is present and if not, I would like have a custom error message. I saw this was asked in Dec, 19. I’m wondering if anything has changed.
ref: Custom type error message
Took me some time to figure it out. I could not see an obvious way to do it inline in the code, but by using an error messages YAML file, I was able to achieve the end I wanted.
With a rule set like:
class UploadContract < Dry::Validation::Contract
config.messages.top_namespace = 'upload_file'
config.messages.default_locale = 'en'
config.messages.load_paths "path/to/errors.yml"
schema do
required(:filename).filled(:string)
required(:import_file).filled(type?: ActionDispatch::Http::UploadedFile)
end
rule(:import_file) do
unless ["text/csv", "text/plain", "application/csv"].include?(values[:import_file].content_type)
key.failure(:invalid_content_type)
end
end
end
And a config like:
en:
upload_file:
errors:
rules:
filename:
filled?: "Must have a filename."
import_file:
filled?: "Upload File Required"
invalid_content_type: "The import file must have a content type of CSV."
Hopefully that helps someone else.
If folks know a better way, please let me know.