【问题标题】:Use validation error values on custom Joi/celebrate messages在自定义 Joi/Celebrate 消息上使用验证错误值
【发布时间】:2020-06-08 10:35:31
【问题描述】:

我正在使用 nodejs/typescript 堆栈为服务器创建一些东西,并且我正在尝试定义自定义通用错误消息而不是每个字段消息。像这样的:

routes.post(
    '/points',
    upload.single('image'), 
    celebrate({
        body: Joi.object().keys({
            name: Joi.string().required(),
            email: Joi.string().required().email(),
            whatsapp: Joi.number().required(),
            latitude: Joi.number().not(0).required(),
            longitude: Joi.number().not(0).required(),
            city: Joi.string().required(),
            uf: Joi.string().required().max(2),
            items: Joi.string().required()
        }),
    }, {
        abortEarly: false,      
        messages: {
            'string.empty':'{context.label} cant be empty!'
        }
    }),
    pointsController.create
);

如您所见,我正在尝试在自定义消息中使用变量/值。我根据来自Celebrate/joi错误的错误条目得到了那个“钥匙”,就像这样:

{
  message: ' cant be empty!',
  path: [ 'items' ],
  type: 'string.empty',
  context: { label: 'items', value: '', key: 'items' }
}

如果有办法做这样的事情? 该消息没有像我想象的那样“解析” {context.label} 。我的意思是,这是在黑暗中拍摄的,因为如果完全支持这样的事情,我找不到任何地方。

【问题讨论】:

    标签: node.js typescript validation joi


    【解决方案1】:

    你可以使用{#label}来实现你想要的。

    试试:

    .messages({
      'string.empty': '{#label} cant be empty!',
      'any.required': '{#label} is a required field for this operation'
    })
    

    对于所有其他类型,依此类推。

    其他值也可以类似地访问。例如,如果您想概括字符串 min/max 的错误消息:

    .messages({
      'string.min': '{#label} should have a minimum length of {#limit}'
    })
    

    这里,限制(分钟)是在您为字符串创建架构时设置的。

    【讨论】:

    • 哦,这就是我得到它们的方式!你有这方面的文档链接吗? (所以我可以找到更多的东西)
    • 当然。 Joi 的 github 文档对此提供了一些理解:github.com/hapijs/joi/blob/master/API.md#template-syntax。要更加熟悉,请在同一页面上阅读更多内容。
    猜你喜欢
    • 2020-09-13
    • 2018-09-29
    • 1970-01-01
    • 2021-08-12
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多