Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 489
Pelumi Avatar asked Mar 25 '26 09:03

Pelumi


2 Answers

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)),
]
like image 73
1565986223 Avatar answered Mar 26 '26 21:03

1565986223


accountNumber inside accounts array is a number whereas req.params.accountNumber is a string. You need to convert the data type. You can do it as

    accountNumberExist(inputAcct) {
        const isfound = accounts.find(account => account.accountNumber.toString() === inputAcct);
        if (isfound === undefined) throw new Error('Account Number not found');
  }
like image 31
Bipin Shrestha Avatar answered Mar 26 '26 21:03

Bipin Shrestha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!