nas*_*shi 5 validation node.js express express-validator nested-fields
我目前正在尝试使用 Express、NodeJs 创建 Rest API 项目,并使用 Express-Validator 来验证请求对象。在一项服务中,我有一个请求正文,例如:
{
"name": "some value",
"surname": "some value",
"company": {
"name": "some value",
"address": "some value"
...
}
}
Run Code Online (Sandbox Code Playgroud)
并尝试验证公司及其子字段(如果公司存在)。
const checkCompany = () => {
return check('company')
.optional()
.custom((company) => {
if (!isEmptyObject(company)) {
[
check('company.name')
.notEmpty().withMessage(CompanyMessages.Name.empty)
.isLength({ min: CompanyConstants.Name.MinLength, max: CompanyConstants.Name.MaxLength }).withMessage(CompanyMessages.Name.length),
check('company.description')
.notEmpty().withMessage(CompanyMessages.Description.empty)
.isLength({ min: CompanyConstants.Description.MinLength, max: CompanyConstants.Description.MaxLength }).withMessage(CompanyMessages.Description.length),
check('company.country')
.notEmpty().withMessage(CompanyMessages.Country.empty),
check('company.city')
.notEmpty().withMessage(CompanyMessages.City.empty),
check('company.address')
.notEmpty().withMessage(CompanyMessages.Address.empty)
.isLength({ min: CompanyConstants.Address.MinLength, max: CompanyConstants.Address.MaxLength }).withMessage(CompanyMessages.Address.length),
]
}
})}
Run Code Online (Sandbox Code Playgroud)
我想要的是:
我可以对所有其他字段和路由使用验证方法,但在这种情况下无法验证字段。我陷入了这种情况,感谢您的帮助,我的代码有什么问题吗?
谢谢
我遇到了同样的问题,我找到了这个解决方案:
使用 :
check('company').optional(),
check('company.name')
.if(body('company').exists()) // check subfield only if 'company' exist
.notEmpty().withMessage(CompanyMessages.Name.empty)
.isLength({ min: CompanyConstants.Name.MinLength, max: CompanyConstants.Name.MaxLength })
.withMessage(CompanyMessages.Name.length),
check('company.description')
.if(body('company').exists()) // check subfield only if 'company' exist
.notEmpty().withMessage(CompanyMessages.Description.empty)
.isLength({ min: CompanyConstants.Description.MinLength, max: CompanyConstants.Description.MaxLength })
.withMessage(CompanyMessages.Description.length),
check('company.country')
.if(body('company').exists()) // check subfield only if 'company' exist
.notEmpty().withMessage(CompanyMessages.Country.empty),
check('company.city')
.if(body('company').exists()) // check subfield only if 'company' exist
.notEmpty().withMessage(CompanyMessages.City.empty),
check('company.address')
.if(body('company').exists()) // check subfield only if 'company' exist
.notEmpty().withMessage(CompanyMessages.Address.empty)
.isLength({ min: CompanyConstants.Address.MinLength, max: CompanyConstants.Address.MaxLength })
.withMessage(CompanyMessages.Address.length),
Run Code Online (Sandbox Code Playgroud)
这个对我有用。
| 归档时间: |
|
| 查看次数: |
4399 次 |
| 最近记录: |