简体   繁体   中英

Joi error message for nested array of object

I have this user input from client side, I'm doing backend validation using Joi.

const Joi = require("joi")

const schema = Joi.array().items(
    Joi.object().required().keys({
      name: 'filter_list',
      value: Joi.array().items(

        Joi.object().required().keys({
          id: 'popular_filters',
          value: Joi.array().required().items(

            Joi.object().required().keys({
              id: Joi.string().required(),
              name: Joi.string().required(),
              items: Joi.array().items(

                Joi.object().keys({
                  id: Joi.string().required(),
                  name: Joi.string().required()
                })

              )
            })

          )
        })
      )
    })
);

// Return result.
const result = Joi.validate([
    {
        name: 'filter_list',
        value: [{
          id: 'popular_filters',
          value: [{
            id: '1',
            name: 'Gym',
            items: [{
              id: 1, // bad error msg
              name: 'x'
            }]
          }]
        }]
      }
], schema);

console.log('error: ', result.error);

demo: https://runkit.com/eldyvoon/5d7b59184bd7b300144a2730

I got error of

Error: "value" at position 0 fails because [child "value" fails because ["value" at position 0 fails because [child "value" fails because ["value" at position 0 fails because [child "items" fails because ["items" at position 0 fails because [child "id" fails because ["id" must be a string]]]]]]]]

by Joi. I don't wish to supply custom error msg but Joi should giv me something like id should be in string not number

Just provide an error function in the chain while defining your schema.

Joi.object().keys({
  id: Joi.string().required().error(new Error('id should be in string not number')),
  name: Joi.string().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