Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate array of objects in express validator

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

You can put check like this, note that arr would be the key in the request body. screenshot from the postman:

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

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

I was able to do it with wildcards like this:

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)

You achieve this by accessing the request body:

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

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

For anyone who wants to validate an array of objects using checkSchema, here's an example where I am validating an array of objects which can have 0 items. You could even do custom validation if you throw a function to do so:

JSON:

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

checkSchema:

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
    }
})