Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I created a model as follow: the model for buying, this used mongoose

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 is the api through which the application can interact

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 this is a request and response made by postman

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

like image 973
Samir Danial Avatar asked Jan 25 '23 06:01

Samir Danial


2 Answers

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()
]
like image 160
kob003 Avatar answered Jan 27 '23 18:01

kob003


Use Wildcard * for nested Objects Read Here

   [
        check('name', " ").not().isEmpty()
        check('productDetails.commdityID', " ").not().isEmpty()
        check('productDetails.totalAmount', " ").not().isEmpty()
    ]
like image 27
Manjeet Thakur Avatar answered Jan 27 '23 20:01

Manjeet Thakur