Car*_*ith 5 javascript arrays express express-validator
我正在尝试使用快速验证器验证对象数组。
我一直在使用新的“通配符”和“自定义”来迭代比较对象上的键的对象数组。
问题是,假设我的对象如下所示:
flavors:[
{ name: '', percentage: '0', ratio: '0' },
{ name: 'Strawberry', percentage: '2', ratio: '0' },
{ name: '', percentage: '3', ratio: '0' }
]
Run Code Online (Sandbox Code Playgroud)
如何仅检查“名称”是否存在“如果”百分比 > 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);
});
Run Code Online (Sandbox Code Playgroud)
这可行,但“错误”输出将类似于:
{ 'flavors[2]': {
location: 'body',
param: 'flavors[2]',
msg: 'Please enter a name for this flavor.',
value: { name: '', percentage: '3', ratio: '0' }
}}
Run Code Online (Sandbox Code Playgroud)
这使得在我的 EJS 模板中显示时变得困难。
如何使用添加的键使输出看起来像这样?
{ 'flavors[2].name': {
location: 'body',
param: 'flavors[2].name',
msg: 'Please enter a name for this flavor.',
value: { name: '', percentage: '3', ratio: '0' }
}}
Run Code Online (Sandbox Code Playgroud)
希望有人能在这里帮助我,谢谢!:-)
目前本机不支持此功能,但当此问题实现时,它可能会部分可用。
现在,在 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;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2930 次 |
| 最近记录: |