在快速验证器中验证对象数组

时间:2018-11-29 11:25:16

标签: node.js express-validator

我正在使用快速验证器来验证我的字段。但是现在我有2或3个对象的数组,其中包含如下所示的“ userId”和“ Hours”字段。

[
  {
    user_id:1,
    hours:8
  },
  {
    user_id:2,
    hours:7
  }
]

现在我需要验证是否 hours或user_id 之类的对象属性为空。如果为空则抛出错误。

5 个答案:

答案 0 :(得分:4)

let arr = [
  {
    user_id:1,
    hours:8
  },
  {
    user_id:2,
    hours:7
  }
]

您可以像这样放置支票:

check("arr.*.user_id")  
  .not()  
  .isEmpty()

check("arr.*.hours")  
  .not()  
  .isEmpty()

答案 1 :(得分:2)

您可以通过访问请求正文来实现:

const { body } = require('express-validator')

body('*.*')
  .notEmpty()

答案 2 :(得分:1)

对于想要使用 checkSchema 验证对象数组的任何人,这里有一个示例,我正在验证可以包含 0 个项目的对象数组。如果您抛出一个函数,您甚至可以进行自定义验证:

JSON:

{
    "employees": [
        {
            "roleId": 3,
            "employeeId": 2,
        },
        {
            "roleId": 5,
            "employeeId": 4,
        },
    ]
}

检查架构:

const customValidator = (async (employees, { req }) => {
    if (!Array.isArray(employees)) {
        return true; // let the base isArray: true validation take over.
    }

    if(!something) {
        throw Error('employee error');
    }

    // validate at your will here. 

    return true;    
}
checkSchema({
    employees: {
        isArray: true,
        min: 0,
        custom: {
            options: customValidator
        },
    },
    "employees.*.roleId": {
        isInt: true
    },
    "employees.*.employeeId": {
        isInt: true
    }
})

答案 3 :(得分:0)

假设您要验证该数组而不是输入,首先必须遍历该对象数组,如下所示:

const array=[{user_id:1,hours:8},{user_id:2,hours:7}]
$.each(array,(key,value)=>{
   //your validation here 
     if(value.user_id.isEmpty()||value.hours.isEmpty())
        {
           //handle this
         }
})

答案 4 :(得分:0)

我能够用这样的通配符做到这一点:

app.post('/users', [
    body().isArray(),
    body('*.user_id', 'user_idfield must be a number').isNumeric(),
    body('*.hours', 'annotations field must a number').exists().isNumeric(),
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
      return res.status(422).json({errors: errors.array()});
  }
 return res.status(200).json(req.body)
相关问题