问题:与
.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
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]
}
]
}