Joi validation of array

后端 未结 6 1036
梦如初夏
梦如初夏 2021-02-02 05:29

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: {
          


        
6条回答
  •  情书的邮戳
    2021-02-02 05:45

    You can also try this way, I have been using it for long time and working fine for me.

    If your array is array of objects than use below:

    const Joi = require('joi');
    
    let schema = Joi.object().keys({
                items: Joi.array().items(
                    Joi.object({
                        item_id: Joi.number().required(),
                        item_qty: Joi.number().required(),
                        item_type_id: Joi.number().required(),
                        item_qty: Joi.number().required(),
                        base_price: Joi.number().required(),
                        actual_price: Joi.number().required(),
                    })
                ).required(),
            });
    
            let errors = Joi.validate(req.body, schema);
    

    if you array is simple array than:

    let schema = Joi.object().keys({
                    items: Joi.array().items(
                    Joi.number().required()
                ).min(10).required(),
                });
    

提交回复
热议问题