Validation contracts (using rules) in actions

I’m confused about parameter validation on Hanami 2.2. I tried to do a password_confirmation validation, but I couldn’t use dry-validation custom rules. I found a reference to a “.confirmation” field on github (Code search results · GitHub), but that didn’t work either.

undefined method `confirmation' for #<Dry::Schema::Macros::Required:

undefined method `rule' for #<Dry::Schema::DSL

What works and what doesn’t work in parameter validation?

Hi @devaniljr, thanks for bringing this here. We actually support what you want: using full dry-validation contracts (which are the ones supporting rule blocks) inside your actions. It was added in this PR (if you’re interested) and released in Hanami 2.2.

To use a contract, you’ll want to switch your action to use contract do instead of params do. This enables the usage of dry-validation contracts inside your action, instead of the simpler dry-schema params schemas that were the only option before.

You’ll want it to look something like this:

# inside your action class
contract do
  params do
    required(:password).filled(:string, min_size?: 8)
    required(:password_confirmation).filled(:string)
  end

  rule(:password_confirmation, :password) do
    if value != values[:password]
      key.failure("must match password") 
    end
  end
end

I’m glad you raised this here, because you highlighted a gap in our documentation. I’ve filed an issue to make sure we do it: Document contract support in actions · Issue #290 · hanami/guides · GitHub

Please let us know how you go with this!

1 Like