如果对象存在,Express 验证器检查嵌套字段

问题描述

我目前正在尝试使用 Express、NodeJs 创建 Rest API 项目,并使用 Express-Validator 来验证请求对象。 在一项服务中,我有一个请求正文,如:

{
  "name": "some value","surname": "some value","company": {
     "name": "some value","address": "some value"
     ...
  }
}

并尝试验证公司及其子字段(如果公司存在)。

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),]
        }
    })}

我想要的是:

  • 如果公司字段不存在,没关系
  • 如果公司字段存在,验证所有子字段

我可以对所有其他字段和路由使用验证方法,但在这种情况下无法验证字段。我被这个案例困住了,感谢您的帮助,我的代码有什么问题?

谢谢

解决方法

我遇到了同样的问题,我找到了这个解决方案:

https://stackoverflow.com/a/64323413/10661841

使用:

 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),

它对我有用。