Costom Joi验证Object.and()的消息

时间:2020-04-15 04:58:55

标签: javascript hapijs joi

我有一个要使用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');

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

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

我希望它返回自定义错误消息,例如。

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验证错误消息,我该怎么做?

1 个答案:

答案 0 :(得分:1)

消息键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!"})
相关问题