Express-Validator 5.2.0 - Validate Wildcard Array Of Objects - Compare
I am trying to validate an array of objects with express-validator. I have been using the new 'wildcard' along with the 'custom', to iterate over the array of objects comparing ke
Solution 1:
For now, can be done this way also
req
.checkBody("flavors","Please enter a name for this flavor.")
.custom(data =>
Array.isArray(data)
&&
data.length
&&
data.every(item => item.name && item.percentage > 0));
I hope it helps :)
Solution 2:
This is not natively supported at the moment, but it may be partially available when this issue gets implemented.
For now, with some help from lodash's _.toPath()
, you can achieve it:
req.checkBody('flavors.*.name').custom((name, { req, location, path }) => {
const index = _.toPath(path)[1];
const { percentage } = req[location].flavors[index];
// If percentage is 0, then it's always valid.
return percentage > 0 ? name !== '' : true;
});
Post a Comment for "Express-Validator 5.2.0 - Validate Wildcard Array Of Objects - Compare"