Joi 将文本/有效值添加到自定义验证功能的错误消息中

问题描述 投票:0回答:1
如果字符串在数组中,我尝试检查 joi 模式(使用自定义验证函数)。

问题:与

.valid()

 中构建的方法相比,错误消息不会打印有效值:

const Joi = require("joi"); const allowed = ["admin", "user", "noob"]; const method = (value, helpers) => { if (!allowed.includes(value)) { return helpers.error("any.only", {allowed}); } return value; }; const createProfileSchema = Joi.object().keys({ username: Joi.string().required().custom(method), text: Joi.string().valid("a", "b") }); const { error, value } = createProfileSchema.validate({ username: "asfd" , text: "c" }, { abortEarly: false }); console.log(error || value);
[Error [ValidationError]: "username" must be one of . "text" must be one of [a, b]] {
  _original: { username: 'asfd', text: 'c' },
  details: [
    {
      message: '"username" must be one of ',
      path: [Array],
      type: 'any.only',
      context: [Object]
    },
    {
      message: '"text" must be one of [a, b]',
      path: [Array],
      type: 'any.only',
      context: [Object]
    }
  ]
}
我如何像

.text

错误消息中那样添加
[admin, user, noob]
部分,完整的错误消息是
"username" must be one of [admin, user, noob]
而不仅仅是
"username" must be one of

    

javascript node.js joi
1个回答
0
投票
我查看了源代码:

https://github.com/hapijs/joi/blob/5b96852fe07a742a8733f2bff1303d50853ca65c/lib/types/any.js#L169C46-L169C52

Joi 需要一个名为“valids”的属性。

return helpers.error("any.only", { valids: allowed });
解决了我的问题。

[Error [ValidationError]: "username" must be one of [admin, user, noob]. "text" must be one of [a, b]] { _original: { username: 'asfd', text: 'c' }, details: [ { message: '"username" must be one of [admin, user, noob]', path: [Array], type: 'any.only', context: [Object] }, { message: '"text" must be one of [a, b]', path: [Array], type: 'any.only', context: [Object] } ] }
    
© www.soinside.com 2019 - 2024. All rights reserved.