最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to implement validation using express-validator for the nested object - Stack Overflow

programmeradmin2浏览0评论

I created a model as follow:

in the model "name", "commodityID", "totalAmount" are required, but notice commodity ID and totalAmount is part of an inner object "productDetails", and now I am using express-validator to do server-side validation as like this

this validation works for "name" fields which make sense but it doesn't work for the "totalAmount" and "commodityID" which are fields of an inner object, and it is the pics I took throw postman

may you guys show me the right way to solve this problem

I created a model as follow:

in the model "name", "commodityID", "totalAmount" are required, but notice commodity ID and totalAmount is part of an inner object "productDetails", and now I am using express-validator to do server-side validation as like this

this validation works for "name" fields which make sense but it doesn't work for the "totalAmount" and "commodityID" which are fields of an inner object, and it is the pics I took throw postman

may you guys show me the right way to solve this problem

Share Improve this question asked Mar 18, 2020 at 6:35 Samir DanialSamir Danial 791 silver badge10 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

for array i.e

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

use

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

For nested object, lets suppose:

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

use

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

Use Wildcard * for nested Objects Read Here

   [
        check('name', " ").not().isEmpty()
        check('productDetails.commdityID', " ").not().isEmpty()
        check('productDetails.totalAmount', " ").not().isEmpty()
    ]
发布评论

评论列表(0)

  1. 暂无评论