【问题标题】:How to implement validation using express-validator for the nested object如何使用 express-validator 对嵌套对象进行验证
【发布时间】:2020-06-29 06:02:42
【问题描述】:

我创建了一个模型如下:

在模型中“name”、“commodityID”、“totalAmount”是必需的,但注意商品ID和totalAmount是内部对象“productDetails”的一部分,现在我使用express-validator进行服务器端验证像这样

此验证适用于有意义的“名称”字段,但不适用于作为内部对象字段的“totalAmount”和“commodityID”, 这是我扔邮递员的照片

你们可以告诉我解决这个问题的正确方法

【问题讨论】:

    标签: javascript arrays node.js express express-validator


    【解决方案1】:

    对于数组

    productDetails: [
      {
        commodityID: {
          type: mongoose.Schema.Types.ObjectId,
          required: true,
          ref: "commodity",
        },
        perOnePrice: { type: String, required: true },
        totalAmount: { type: Number, required: true },
        
      },
    ],
    

    使用

    [
     body('productDetails.*.commodityID').not().isEmpty()
     body('productDetails.*.perOnePrice').not().isEmpty()
     body('productDetails.*.totalAmount').not().isEmpty()
    ]
    

    对于嵌套对象,假设:

    productDetails: {
        commodityID: {
          type: mongoose.Schema.Types.ObjectId,
          required: true,
          ref: "commodity",
        },
        perOnePrice: { type: String, required: true },
        totalAmount: { type: Number, required: true },      
      },
    

    使用

    [
     body('productDetails.commodityID').not().isEmpty()
     body('productDetails.perOnePrice').not().isEmpty()
     body('productDetails.totalAmount').not().isEmpty()
    ]
    

    【讨论】:

      【解决方案2】:

      对嵌套对象使用通配符 * Read Here

         [
              check('name', " ").not().isEmpty()
              check('productDetails.commdityID', " ").not().isEmpty()
              check('productDetails.totalAmount', " ").not().isEmpty()
          ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多