数组的Joi验证 [英] Joi validation of array

查看:274
本文介绍了数组的Joi验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图验证数组在一种情况下是否包含零个或多个字符串,而在另一种情况下尝试零个或多个对象,这与Joi docs苦苦挣扎:(

trying to validate that an array has zero or more strings in one case and that it has zero or more objects in another , struggling with Joi docs :(

validate: {
        headers: Joi.object({
                'content-type': "application/vnd.api+json",
                accept: "application/vnd.api+json"
        }).options({ allowUnknown: true }),
        payload : Joi.object().keys({
            data : Joi.object().keys({
                type: Joi.any().allow('BY_TEMPLATE').required(),
                attributes: Joi.object({
                    to : Joi.string().email().required(),
                    templateId : Joi.string().required(),
                    categories : Joi.array().items( //trying to validate here that each element is a string),
                    variables : Joi.array({
                        //also trying to validate here that each element is an Object with one key and value
                    })
                })
            }).required()
        })
    }

推荐答案

Joi.array().items()接受另一个Joi模式来对数组元素使用.因此,字符串数组很简单:

Joi.array().items() accepts another Joi schema to use against the array elements. So an array of strings is this easy:

Joi.array().items(Joi.string())

与一组对象相同;只需将对象架构传递给items():

Same for an array of objects; just pass an object schema to items():

Joi.array().items(Joi.object({
    // Object schema
}))

这篇关于数组的Joi验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆