简体   繁体   English

嵌套验证中的hapi / joi描述性错误

[英]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 ) 我正在尝试使用https://github.com/hapijs/joi进行对象验证的嵌套数组,我的代码如下( 此处是操场)

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. 然后,前端将无法通过错误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. “ error()”采用错误的实例或函数。 https://hapi.dev/family/joi/?v=16.1.4#anyerrorerr 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? 也许您可以在这里找到更多有用的信息: Node.js + Joi如何显示自定义错误消息?

Hope this helps as I'm not exactly sure of what you are asking for. 希望这会有所帮助,因为我不确定您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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