Specifying rule on a field in a hash in an array

Upgrading to dry-validation 1.x, we’d like to validate a structure that looks like this:

{
  phones: [
    {
      number: "13035551234"
    }
  ]
}
      params do
        required(:phones).filled.array(:hash) do
          required(:number).value(PhoneNumber::Type, :filled?)
          optional(:type).maybe(:str?)
        end

      rule(:phones).each do
        key.failure("does not seem to be possible") unless PhoneNumber.build(value[:number]).possible?
      end
    end

In the previous version of dry-validate, the errors.to_h came back looking like:

{:phones => {0=>{:number=>["phone does not seem to be possible"]}}}

And in 1.x, it looks like:

{:phones => {0=>["does not seem to be possible"]}}

How do you specify the rule should match on a hash nested in an array? So far I’ve tried:

rule(:phones).each do
  rule(:number) do # undefined method `rule' for #<Dry::Validation::Evaluator:0x000055b9a92786f8>

rule("phones.number") do
rule(phones: number) do # .rule specifies keys that are not defined by the schema

Is there some other way to specify this, or is it just not supported (yet)?

You can do this:

key([*path, :number]).failure("does not seem to be possible") unless PhoneNumber.build(value[:number]).possible?

In the future there will be a way of specifying a path including array members, ie rule("phones[].number") or something like this.

1 Like