简体   繁体   中英

hapi/joi descriptive error in nested validation

I'm trying to use https://github.com/hapijs/joi to do nested array of object validation, my code as below (playground here )

const Joi = require("@hapi/joi")

const schema = Joi.array().required().items(
        Joi.object().required().keys({
            name: 'room_range',
            value: Joi.object({
                min: Joi.number().required(),
                max: Joi.number().min(Joi.ref('min')).required()
            })
        }),

        Joi.object().required().keys({
            name: 'anything',
            value: Joi.object({
                min: Joi.number().required(),
                max: Joi.number().min(Joi.ref('min')).required() 
            })
        }),
    )

const result = schema.validate([
    {
        name: 'room_range',
        value: {
         min: 'dddd',
         max: 2
        }
      },{
       name: 'anything',
       value: {
         min: 1,
         max: 2
       }
      }
]);

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

I got this error

exports.ValidationError: "value" does not contain 1 required value(s)

Then the frontend will not be able to know by the error msg.

You could try this:

value: Joi.object({
  min: Joi.number().required().error(() => 'error message here'),
  max: Joi.number().min(Joi.ref('min')).required().error(() => 'error message here'),
}),

If you need an error message on the object or array you should be able to do the same thing just on the object.

value: Joi.object({
  min: Joi.number().required(),
  max: Joi.number().min(Joi.ref('min')).required(),
}).required().error(() => 'error message here'),

The 'error()' takes either an instance of error or a function. https://hapi.dev/family/joi/?v=16.1.4#anyerrorerr

Maybe you can find more usefull info here: Node.js + Joi how to display a custom error messages?

Hope this helps as I'm not exactly sure of what you are asking for.

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