如何使用 body() 在 express-validator 中验证 arrays/objects,只检查指定的字段?
How to validate arrays/objects in express-validator using body(), checking only the specified fields?
我的字段名称在这样的数组中:
const baseFields = [
'employeeNumber',
'firstName',
'lastName',
'trEmail',
'position'
];
这些是我只需要关心的输入字段。
在请求正文中,我收到了一个对象数组。
示例:
{employeeNumber: 12343,
firstName: Will,
lastName: Smith,
trEmail: smith@will.com,
position: Actor,
salary: low
},
{employeeNumber: 12344,
firstName: Chris,
lastName: Rock,
trEmail: rock@chris.com,
position: stuntman,
salary: ''
}
我想仅使用 baseFields
数组中的关注字段来验证此数组。
这是我当前的验证器代码。我发现我可以使用通配符来验证数组。
const existsOptions = {
checkNull: true,
checkFalsy: true
};
const postRequiredFields = () => {
const validators = [];
const validator = body('*.*')
.exists(existsOptions)
.bail()
.isString();
validators.push(validator);
return validators;
};
使用此 const validator = body('*.*')
将检查主体中对象数组中的所有字段。由于我可以收到此消息:
{ value: '',
msg: 'Invalid value',
param: '[1].salary',
location: 'body' }
你看,salary
字段正在检查中。它返回无效值,因为数组中的第二个索引将薪水设置为 '' 或为空。但同样,工资字段不是我需要验证的字段之一。
所以我尝试了类似这样的方法 body('baseFields*.*')
来检查整个对象数组,但只检查关注字段,但它不起作用。我无法在线为我的场景找到正确的通配符模式。文档也说的很少。
要检查数组中的对象,请使用:*.key
然后您可以循环您的密钥并动态添加它们:
const postRequiredFields = () => {
const validators = [];
baseFields.map((key) => {
const validator = body(`*.${key}`)
.exists(existsOptions)
.bail()
.isString();
validators.push(validator);
});
return validators;
};
我的字段名称在这样的数组中:
const baseFields = [
'employeeNumber',
'firstName',
'lastName',
'trEmail',
'position'
];
这些是我只需要关心的输入字段。
在请求正文中,我收到了一个对象数组。 示例:
{employeeNumber: 12343,
firstName: Will,
lastName: Smith,
trEmail: smith@will.com,
position: Actor,
salary: low
},
{employeeNumber: 12344,
firstName: Chris,
lastName: Rock,
trEmail: rock@chris.com,
position: stuntman,
salary: ''
}
我想仅使用 baseFields
数组中的关注字段来验证此数组。
这是我当前的验证器代码。我发现我可以使用通配符来验证数组。
const existsOptions = {
checkNull: true,
checkFalsy: true
};
const postRequiredFields = () => {
const validators = [];
const validator = body('*.*')
.exists(existsOptions)
.bail()
.isString();
validators.push(validator);
return validators;
};
使用此 const validator = body('*.*')
将检查主体中对象数组中的所有字段。由于我可以收到此消息:
{ value: '',
msg: 'Invalid value',
param: '[1].salary',
location: 'body' }
你看,salary
字段正在检查中。它返回无效值,因为数组中的第二个索引将薪水设置为 '' 或为空。但同样,工资字段不是我需要验证的字段之一。
所以我尝试了类似这样的方法 body('baseFields*.*')
来检查整个对象数组,但只检查关注字段,但它不起作用。我无法在线为我的场景找到正确的通配符模式。文档也说的很少。
要检查数组中的对象,请使用:*.key
然后您可以循环您的密钥并动态添加它们:
const postRequiredFields = () => {
const validators = [];
baseFields.map((key) => {
const validator = body(`*.${key}`)
.exists(existsOptions)
.bail()
.isString();
validators.push(validator);
});
return validators;
};