用于数组验证的干式验证 i18n 消息
Dry validation i18n message for array validation
假设我定义了一个 dry-validation 这样的:
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
这是我的 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'
在我的代码中,我用它来验证我的数据:
my_json = create_my_json
v = ApplicationContract.new
result = v.call(my_json)
render json: result.errors(locale: :vi).to_h
- 如果my_json喜欢:
{
“标题”: ””,
“项目”: [
{
“名称”:“bb”
}
]
}
然后我得到回复:
{
"todo": {
"title": [
"phai duoc dien"
]
}
}
你们可以看到我对字段标题的验证在 locale vi 下工作得很好
- 现在如果我的 json 喜欢:
{
“标题”:“aa”,
“项目”: [
{
“名称”: ””
}
]
}
那么响应是:
{
"todo": {
"items": {
"0": {
"name": [
"translation missing: vi.dry_validation.errors.filled?"
]
}
}
}
}
验证仍然有效,但无法获取我的语言环境消息。它显示警告“翻译缺失:vi.dry_validation.errors.filled?”反而。我该如何解决这个问题?
终于明白了。只需从 config/errors.yml:
中删除节点项
vi:
dry_validation:
errors:
rules:
title:
filled?: 'phai duoc dien'
key?: 'ko dc trong'
name:
key?: 'thieu name'
filled?: 'name rong'
假设我定义了一个 dry-validation 这样的:
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
这是我的 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'
在我的代码中,我用它来验证我的数据:
my_json = create_my_json
v = ApplicationContract.new
result = v.call(my_json)
render json: result.errors(locale: :vi).to_h
- 如果my_json喜欢: { “标题”: ””, “项目”: [ { “名称”:“bb” } ] }
然后我得到回复:
{
"todo": {
"title": [
"phai duoc dien"
]
}
}
你们可以看到我对字段标题的验证在 locale vi 下工作得很好
- 现在如果我的 json 喜欢: { “标题”:“aa”, “项目”: [ { “名称”: ”” } ] }
那么响应是:
{
"todo": {
"items": {
"0": {
"name": [
"translation missing: vi.dry_validation.errors.filled?"
]
}
}
}
}
验证仍然有效,但无法获取我的语言环境消息。它显示警告“翻译缺失:vi.dry_validation.errors.filled?”反而。我该如何解决这个问题?
终于明白了。只需从 config/errors.yml:
中删除节点项vi:
dry_validation:
errors:
rules:
title:
filled?: 'phai duoc dien'
key?: 'ko dc trong'
name:
key?: 'thieu name'
filled?: 'name rong'