簡體   English   中英

在自定義 Joi/Celebrate 消息上使用驗證錯誤值

[英]Use validation error values on custom Joi/celebrate messages

我正在使用服務器的 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} 。 我的意思是,這是在黑暗中拍攝的,因為如果完全支持這樣的事情,我找不到任何地方。

您可以使用{#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}'
})

在這里,限制 (min) 在您為字符串創建架構時設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM