Dry-validation and unique validation


Is there a way to handle unique validation ?

For example, if an user’s email must be unique


I found the solution.

I must inject the repository in the schema, and then create a method “is_name_available” in my repository, to check if the name is taken or not.

CompanySchema = Dry::Validation.Schema do
  configure do
    config.messages_file = 'config/schema_errors.yml'
    option :company_repository, CompanyRepository

    def unique_company_name?(value)

  required(:name).filled(:str?, :unique_company_name?)


This solution is subject to race conditions. More “robust” way to do unique validation is to create a unique database constraint for the validated column (i.e., email) and rescue from unique constraint violation error. It’s out of the scope of dry-validation though.