egg-validate进行参数校验如何校验数组array和对象类型?多层嵌套,都需要校验

一、普通一层参数的校验方法是这样的:

const rule = {
      goodsId: { type: 'number', required: true },
      name: { type: 'string', required: false },
      categoryId: { type: 'number', required: false },
      unitName: { type: 'string', required: false },
      salePrice: { type: 'number', required: false },
      spec: { type: 'string', required: false },
      thumbnail: { type: 'string', required: false },
      imagesPic: { type: 'string', required: false },
      goodsInfo: { type: 'string', required: false },
    };
    ctx.validate(rule,  ctx.request.body);

注:validate()第二个参数不传,默认就是取的ctx.request.body。

二、如何进行嵌套的数组或对象校验呢?

我们查看egg-validator源码,发现它其实是引用的parameter这个框架。

网上分析源码的那个,答案是错误的。

其实,我们去查看parameter的README.md文档其实就能够找到答案

在这里插入图片描述
所以,正确的方式是如下:

const rule = {
      products: {
        type: 'array',
        itemType: 'object',
        rule: {
          goodsSN: { type: 'string', required: true }, // 商品规格名称
          goodsId: { type: 'number', required: true },
          goodsNumber: { type: 'number', required: true }, // 单价
        },

      },

    };
    ctx.validate(rule);

那么当我们输入错误的参数时,返回的提示信息如下:

{
    "code": 500,
    "message": "Validation Failed",
    "detail": [
        {
            "message": "required",
            "field": "products[0].goodsId",
            "code": "missing_field"
        },
        {
            "message": "required",
            "field": "products[0].goodsNumber",
            "code": "missing_field"
        }
    ]
}

当然,返回接口是是处理过了的。大家查看错误提示信息就可以了。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值