Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
Express-Validator Check array of Subdocuments

This is my Schema:

const InvoiceSchema = new Schema({
name: { type: String, required: true },
description: { type: String },

items: [{
    name: { type: String, required: true },
    rate: { type: Number, required: true },
    quantity: { type: Number, required:true, default: 1 },
    amount: { type: Number }
}]});

I want to know how to use Express-validator to check items elements?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Had the same problem before and its very painful especially if its a deep array or array of objects to validate. I ended up creating my own validator (wallter) that will handle this issue. And also this tool can generate validation schema straight from your mongoose model.

So your schema above will generate a validation schema:

{
  "name": {
    "required": {
      "msg": "Value for field 'name' is required"
    }
  },
  "description": {
    "optional": true
  },
  "items.*.name": {
    "required": {
      "msg": "Value for field 'items.*.name' is required"
    }
  },
  "items.*.rate": {
    "required": {
      "msg": "Value for field 'items.*.rate' is required"
    },
    "isDecimal": {
      "msg": "Expecting 'decimal' value for field 'items.*.rate'"
    }
  },
  "items.*.quantity": {
    "required": {
      "msg": "Value for field 'items.*.quantity' is required"
    },
    "isDecimal": {
      "msg": "Expecting 'decimal' value for field 'items.*.quantity'"
    }
  },
  "items.*.amount": {
    "optional": true,
    "isDecimal": {
      "msg": "Expecting 'decimal' value for field 'items.*.amount'"
    }
  }
}

This validation schema can be fed to validator

const halter = require('wallter').halter
const Builder = require('wallter').builder // validation schema builder

const builder = new Builder({
  model: mongoose.model('YourModelName')
})

server.use(halter())

server.post('/test', function (req, res, next) {
    let validationSchema = builder.build() // see above generated validation schema output

    req.halt(validationSchema).then(result => {
        if (result.length) {
            res.send(400, result)
        } else {
            res.send(200)
        }

        return next()
    })
})
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!