我正在尝试使用 express-validator 验证一组对象。
我一直在使用新的“通配符”和“自定义”来遍历比较对象上的键的对象数组。
这是问题所在,假设我的对象看起来像这样:
flavors:[
{ name: '', percentage: '0', ratio: '0' },
{ name: 'Strawberry', percentage: '2', ratio: '0' },
{ name: '', percentage: '3', ratio: '0' }
]
如何只检查“名称”是否存在“如果”百分比 > 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);
});
这可行,但“错误”输出类似于:
{ 'flavors[2]': {
location: 'body',
param: 'flavors[2]',
msg: 'Please enter a name for this flavor.',
value: { name: '', percentage: '3', ratio: '0' }
}}
这使得在我的 EJS 模板中显示时变得困难。
如何使用添加的 key 使输出看起来像这样?
{ 'flavors[2].name': {
location: 'body',
param: 'flavors[2].name',
msg: 'Please enter a name for this flavor.',
value: { name: '', percentage: '3', ratio: '0' }
}}
希望有人能帮帮我,谢谢! :-)
最佳答案
这目前不受本地支持,但可能会在 this issue 时部分可用。得到实现。
现在,在 lodash 的 _.toPath()
的帮助下,你可以实现它:
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;
});
关于javascript - Express-Validator 5.2.0 - 验证对象的通配符数组 - 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51114028/