Joi validation of array

折月煮酒 提交于 2019-12-03 08:12:45

问题


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()
        })
    }

回答1:


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())

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

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



回答2:


you can try this:

function(data){
const Schema = {

categories: Joi.array().items(Joi.string()),
variables: Joi.array().items(Joi.object().keys().min(1))

}

return Joi.validate(data, Schema)

}



回答3:


Joi.array().items(Joi.string().required(), Joi.number().required()); found it here




回答4:


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(Joi.string()),
                    variables : Joi.array().items(Joi.object().keys().max(1))
                })
            }).required()
        })
    }


来源:https://stackoverflow.com/questions/42656549/joi-validation-of-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!