Search code examples
rubydry-validation

Dry validation i18n message for array validation


Let say I have define a dry-validation like this:

class ApplicationContract < Dry::Validation::Contract
  config.messages.backend = :i18n
  config.messages.load_paths << 'config/errors.yml'

  params do
    required(:todo).schema do
      required(:title).filled(:string)
      required(:items).array(:hash) do
        required(:name).filled(:string)
      end
    end
  end
end

Here is my config/errors.yml:

vi:
  dry_validation:
    errors:
      rules:
        title:
          filled?: 'phai duoc dien'
          key?: 'ko dc trong'
        items:
          name:
            key?: 'thieu name'
            filled?: 'name rong'

In my code, I use it to validate my data:

my_json = create_my_json
v = ApplicationContract.new
result = v.call(my_json)
render json: result.errors(locale: :vi).to_h
  1. If my_json like: { "title": "", "items": [ { "name": "bbb" } ] }

then I got response:

{
    "todo": {
        "title": [
            "phai duoc dien"
        ]
    }
}

You guys can see my validation for field title works fine with locale vi

  1. Now if my json like: { "title": "aa", "items": [ { "name": "" } ] }

then the response is:

{
    "todo": {
        "items": {
            "0": {
                "name": [
                    "translation missing: vi.dry_validation.errors.filled?"
                ]
            }
        }
    }
}

The validation still works but it can not get my locale message. It show the warning "translation missing: vi.dry_validation.errors.filled?" instead. How can I fix this problem?


Solution

  • Finally I got it. Just remove the node items from config/errors.yml:

    vi:
      dry_validation:
        errors:
          rules:
            title:
              filled?: 'phai duoc dien'
              key?: 'ko dc trong'
            name:
              key?: 'thieu name'
              filled?: 'name rong'