How to validate array of objects using Joi?

前端 未结 5 1435
猫巷女王i
猫巷女王i 2020-12-29 01:28

I am getting an array of objects to backend, where each object contains a service name. The structure looks like below

[{\"serviceName\":\"service1\"},
{\"s         


        
5条回答
  •  太阳男子
    2020-12-29 02:01

    For Joi you can use below which is working fine for me, this will validate that array must have at-least on object with key serviceName-

    const Joi = require('joi');
    const itemsArray = Joi.array().items(
                Joi.object({
                    serviceName: Joi.string().required(),
                })
            ).min(1).required();
    
            const itemSchema = Joi.array().items(itemsArray).when('checkout_type', {
                is: 'guest',
                then: Joi.array().required(),
            }).required();
    
    let schema = Joi.object().keys({
            items: Joi.alternatives().try(itemsArray, itemSchema).required(),
        });
    

提交回复
热议问题