# Dry-validation and unique validation

**URL:** <https://discourse.dry-rb.org/t/dry-validation-and-unique-validation/529>\
**Category:** dry-validation\
**Created:** [April 9, 2018, 9:05am UTC](https://discourse.dry-rb.org/t/dry-validation-and-unique-validation/529 "2018-04-09T09:05:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![xero88](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/xero88/32/247_2.png) [@xero88](https://discourse.dry-rb.org/u/xero88)\
**Post date:** [April 9, 2018, 9:05am UTC](https://discourse.dry-rb.org/t/dry-validation-and-unique-validation/529/1 "2018-04-09T09:05:39Z")

</div>

Is there a way to handle unique validation ?

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

---

<div class="post-metadata">

**Author:** ![xero88](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/xero88/32/247_2.png) [@xero88](https://discourse.dry-rb.org/u/xero88)\
**Post date:** [April 9, 2018, 9:23am UTC](https://discourse.dry-rb.org/t/dry-validation-and-unique-validation/529/2 "2018-04-09T09:23:30Z")

</div>

**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
```

---

<div class="post-metadata">

**Author:** ![smaximov](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.dry-rb.org/smaximov/32/165_2.png) [@smaximov](https://discourse.dry-rb.org/u/smaximov)\
**Post date:** [April 13, 2018, 3:46pm UTC](https://discourse.dry-rb.org/t/dry-validation-and-unique-validation/529/3 "2018-04-13T15:46:33Z")

</div>

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.
