Full error messages work fine when I pass a string message, e.g. key.failure("is invalid")
. The full message includes the translated key (e.g. "Full Name is invalid"
), or the key itself if there’s no translation (e.g. "full_name is invalid"
)
However, if I pass a symbol, e.g. key.failure(:invalid)
, and the rule has no translation, the full error message will not include the key (e.g. " is invalid"
)
require "i18n"
require "dry/validation"
I18n.backend.store_translations(
:en,
{
dry_validation: {
rules: {
foo: "Translated Foo"
},
errors: {
is_invalid: "is invalid"
}
}
}
)
class WithStringMessages < Dry::Validation::Contract
config.messages.backend = :i18n
params do
required(:foo).value(:integer)
required(:bar).value(:integer)
end
rule(:foo) do
key.failure("is invalid") if value < 0
end
rule(:bar) do
key.failure("is invalid") if value < 0
end
end
class WithSymbolMessages < Dry::Validation::Contract
config.messages.backend = :i18n
params do
required(:foo).value(:integer)
required(:bar).value(:integer)
end
rule(:foo) do
key.failure(:is_invalid) if value < 0
end
rule(:bar) do
key.failure(:is_invalid) if value < 0
end
end
puts WithStringMessages.new.call(foo: -1, bar: -1).errors(full: true).map(&:text).inspect
#=> ["Translated Foo is invalid", "bar is invalid"]
puts WithSymbolMessages.new.call(foo: -1, bar: -1).errors(full: true).map(&:text).inspect
#=>["Translated Foo is invalid", " is invalid"]
It is especially relevant when I want to use a dry-logic predicate as a macro.
rule(:foo).validate(gt?: 0)
# full error message for that: " must be greater than 0"
I think there’s no issue with adding a fallback to the key name if it couldn’t find the translation.
I’m keen to open an Issue/PR for that, but wanted to discuss it here first.
Thanks.
ruby 2.6.6
dry-validation 1.5.2