dry-rb/dry-validation

Rule validation does not show in errors when the key validated is in an array of hashes

Open

#722 opened on Dec 1, 2022

View on GitHub
 (1 comment) (0 reactions) (0 assignees)Ruby (193 forks)github user discovery
bughelp wanted

Repository metrics

Stars
 (1,421 stars)
PR merge metrics
 (PR metrics pending)

Description

Describe the bug

Rule validation does not show in errors when the key validated is in an array of hashes

To Reproduce

Provide detailed steps to reproduce, an executable script would be best.

  1. Define the contract
#address_contract.rb
class AddressContract < Dry::Validation::Contract
  json do
    required(:street_address).filled(:string)
    required(:country).filled(:string)
  end
end
  1. define another contract that uses AddressContract
#new_user_contract.rb
class NewUserContract < Dry::Validation::Contract
  json do
    required(:user_details).array(:hash) do
      required(:email).filled(:string)
      required(:address).hash(AddressContract.schema)
    end
  end

  rule(:user_details).each do
    unless /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i.match?(value[:email])
      key.failure('has invalid format')
    end
  end
end
  1. Create the contract
contract = NewUserContract.new
  1. Validate the following payload
payload = {
   user_details: [{email: 'jane', address: '17'}]
 }
 
 contract.call(payload)

Expected behavior

expected output

> #<Dry::Validation::Result{:user_details=>[{:email=>"jane", :address=>"17"}]} errors={:user_details=>{0=>{:email=>["has invalid format"], :addresss=>["must be a hash"]}}}>

but got

> #<Dry::Validation::Result{:user_details=>[{:email=>"jane", :address=>"17"}]} errors={:user_details=>{0=>{:address=>["must be a hash"]}}}>

As you can see, it is missing the rule validation for the format of the email. Is this a bug? Or am I missing something here?

My environment

  • Affects my production application: YES/NO
  • Ruby version: 3.1.2
  • OS: MacOS M1

Contributor guide