I’m trying to catch unexpected keys in my (Rails-) API, using the following (simplified) code:
require "dry-validation"
class C < Dry::Validation::Contract
config.validate_keys = true
params do
required(:name).filled :string
optional(:tel).maybe(:array).each do
hash do
required(:number).value :string, :filled?
optional(:note).maybe :string
end
end
end
end
(pp C.new)
#<C
schema=#<Dry::Schema::Params
keys=["name", {"tel"=>["number", "note"]}]
rules={
:name=>"key?(:name) AND key[name](filled? AND str?)",
:tel=>"
key?(:tel) THEN key[tel](
not(nil?) THEN array? AND each(
hash? AND set(
key?(:number) AND key[number](str? AND filled?),
key?(:note) THEN key[note](not(nil?) THEN str?)
)
)
)
"
}
>
rules=[]
>
An unspecified (top-level) key returns an error, as expected:
pp C.new.call(name: "Mario", random: 42, tel: [])
#=> #<Dry::Validation::Result{:name=>"Mario", :tel=>[]}
# errors={:random=>["is not allowed"]}>
However, filling the :tel
array returns an unexpected error:
pp C.new.call(name: "Luigi", tel: [{ number: "+1555123456" }])
#=> #<Dry::Validation::Result{:name=>"Luigi", :tel=>[{:number=>"+1555123456"}]}
# errors={:tel=>{0=>{:number=>["is not allowed"]}}}>
I’m not entirely sure what’s happening here. Am I doing something wrong?