Validate array of objects in express validator

user10298495 picture user10298495 · Nov 29, 2018 · Viewed 13.1k times · Source

I am using express validator to validate my fields. But now i have array of 2 or 3 objects, which contains the "userId" and "Hours" fields like below.

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

Now i need to validate, if any of object property like hours or user_id is empty or not.if empty throw it's error.

Answer

Nikhil Prabhakar picture Nikhil Prabhakar · Dec 11, 2018
let arr = [
  {
    user_id:1,
    hours:8
  },
  {
    user_id:2,
    hours:7
  }
]

You can put check like this:

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

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