Struggling to validate an array of objects using express-validator.
Utilizing the "wildcard" and "custom", I'm looping through the objects in the array to compare keys.
The issue arises with an object structured like this:
flavors:[
{ name: '', percentage: '0', ratio: '0' },
{ name: 'Strawberry', percentage: '2', ratio: '0' },
{ name: '', percentage: '3', ratio: '0' }
]
I need to check if "name" is present only when "percentage" > 0.
req.checkBody("flavors","Your recipe has no flavor!").notEmpty();
req.checkBody("flavors.*","Please enter a name for this flavor.").custom(function (value) {
return (!(value.percentage > 0) && !value.name);
});
This setup functions, but the error output format can be challenging:
{ 'flavors[2]': {
location: 'body',
param: 'flavors[2]',
msg: 'Please enter a name for this flavor.',
value: { name: '', percentage: '3', ratio: '0' }
}}
Displaying this in my EJS template becomes complex. How can I modify the output to include an additional key?
{ 'flavors[2].name': {
location: 'body',
param: 'flavors[2].name',
msg: 'Please enter a name for this flavor.',
value: { name: '', percentage: '3', ratio: '0' }
}}
Appreciate any assistance on resolving this, thank you! :-)