Dry-validation and unique validation


#1

Is there a way to handle unique validation ?

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


#2

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)
      company_repository.is_name_available?(value)
    end
  end

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

#3

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.