简体   繁体   中英

Costom Joi validation message for Object.and()

I have a schema that I want to validate using 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');

By default it return a validation error message like.

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

I want it to return a custom error message like.

Username, Birthyer and Nick name all are required!

For custom message say nickname I would do something like below

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

So, I tried below, but It doesn't work.

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!"})

How can I do something same for Object.and validation error message?

The message key string.base overrides string validation messages

In your case you should use 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!"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM