如何使用验证在post方法中声明数组

时间:2014-08-05 13:30:10

标签: node.js express

在我的项目中,我想在post方法中验证缺少的字段。我表中的字段如下所示:

{
  name: string, required: true
  products: [
    {
      name: string, required: true
      quantity: number, required: true
      rate: number
    }
  ]

现在我声明对name字段的验证如下:

req.checkBody('name','Missing params').notEmpty();

它工作正常,但数组不工作,代码是:

req.checkBody(products: 'name','Missing params').notEmpty();         
req.checkBody(products: 'quantity','Missing params').notEmpty();

1 个答案:

答案 0 :(得分:2)

如果要验证an array in a nested object,则必须传递数组。而不是这样做:

req.checkBody(products: 'name','Missing params').notEmpty();
req.checkBody(products: 'name','Missing params').notEmpty();

,你应该这样做:

req.checkBody(['products', 0, 'name'],'Missing params').notEmpty();
req.checkBody(['products', 0, 'quantity'],'Must be an integer').isInt();

,等等。