Search code examples
javascriptapiexpressendpointexpress-validator

Validating req.params with express validator


I want the user to be able to write a specific account number in the endpoint, been trying to validate the endpoint param if it exists in my database. I couldn't get it to work, please what am I doing wrong?

My validation

const validateReq: [
param('accountNumber').exists().custom(acctNo => accountNumberExist(acctNo)),]

My accountNumberExist function

    accountNumberExist(inputAcct) {
    const isfound = accounts.find(account => account.accountNumber === inputAcct);
    if (isfound === undefined) throw new Error('Account Number not found');
  }

My accounts file

    const accounts = [
  {
    id: 1,
    accountNumber: 1234567890,
    createdOn: new Date(),
    owner: 1,
    type: 'current',
    balance: 23444.43,
    status: 'active',
  },
  {
    id: 2,
    accountNumber: 1234167890,
    createdOn: new Date(),
    owner: 1,
    type: 'savings',
    balance: 2233444.43,
    status: 'active',
  },
  {
    id: 3,
    accountNumber: 9987654321,
    createdOn: new Date(),
    owner: 2,
    type: 'saving',
    balance: 73444.43,
    status: 'active',
  },
];

But this is always throwing the 'Account Number not found' error even though, the req.param exists in my accounts database.


Solution

  • Params are parsed as string by express middleware. Say I make a req to path defined below like /some/1000

    app.get('/some/:path', (req, res, next) => {
      console.log(typeof req.param.path)
      // outputs string
    })
    

    So you need to parse the incoming parameter to integer (Number) since you've stored accountNumber as integer. So adding toInt to chain like below should solve it:

    const validateReq: [
      param('accountNumber').exists().toInt().custom(acctNo => accountNumberExist(acctNo)),
    ]