Object.and() 的自定义 Joi 验证消息

Costom Joi validation message for Object.and()

我有一个要使用 Ojbect.and().

验证的架构
const schema = Joi.object().keys({
    username: Joi.string().alphanum().min(3).max(30).required(),
    password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
    access_token: [Joi.string(), Joi.number()],
    birthyear: Joi.number().integer().min(1900).max(2013),
    email: Joi.string().email(),
    nickname: Joi.string()
}).and('username', 'birthyear', 'nickname').without('password', 'access_token');

默认情况下它 return 验证错误消息,例如。

"\"value\" contains [username] without its required peers [birthyear, nickname]"

我想要它 return 自定义错误消息,例如。

Username, Birthyer and Nick name all are required!

对于自定义消息说 nickname 我会做类似下面的事情

Joi.string().messages({ 'string.base' : "Nickname should be string!"})

所以,我在下面尝试过,但它不起作用。

const schema = Joi.object().keys({
    username: Joi.string().alphanum().min(3).max(30).required(),
    password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
    access_token: [Joi.string(), Joi.number()],
    birthyear: Joi.number().integer().min(1900).max(2013),
    email: Joi.string().email(),
    nickname: Joi.string()
})
.and('username', 'birthyear', 'nickname').without('password', 'access_token')
.messages({ 'Object.and' : "Username, Birthyear and Nick name all are required!"})

如何对 Object.and 验证错误消息做同样的事情?

消息键 string.base 覆盖字符串验证消息

在您的情况下,您应该使用 object.and

const schema = Joi.object().keys({
    username: Joi.string().alphanum().min(3).max(30).required(),
    password: Joi.string().pattern(/^[abc]+$/),
    access_token: [Joi.string(), Joi.number()],
    birthyear: Joi.number().integer().min(1900).max(2013),
    email: Joi.string().email(),
    nickname: Joi.string()
})
.and('username', 'birthyear', 'nickname').without('password', 'access_token')
.messages({ 'object.and' : "Username, Birthyear and Nick name all are required!"})