medkhelifi
medkhelifi

Reputation: 1121

Node Js Express validator Check if field is numeric only if it is not empty

I use express-validator to check my post fields, one of my field must be a decimal or empty. I used this Schema:

request.checkBody({ 
        'product_price': {
            optional: true,
            isDecimal: {
                errorMessage: 'The product price must be a decimal'
            }
        }
})

The problem with this Schema is to not validate my post if product_price is empty, even with "optional: true".

Upvotes: 6

Views: 27553

Answers (3)

beingyogi
beingyogi

Reputation: 1416

In case if someone is using express-validator body. You can do the following thing

router.post('apiname', [
  body('product_price').trim()
    .optional({ checkFalsy: true })
    .isNumeric().withMessage('Only Decimals allowed'),
])

Upvotes: 1

robertklep
robertklep

Reputation: 203514

You need to set the checkFalsy option for optional to allow defined-but-empty values:

request.checkBody({ 
  'product_price': {
    optional: {
      options: { checkFalsy: true }
    },
    isDecimal: {
      errorMessage: 'The product price must be a decimal'
    }
  }
});

EDIT: the documentation has been moved since posting this answer, it can now be found here.

Upvotes: 16

octopushugs
octopushugs

Reputation: 157

What worked for me was using req.checkBody('optionalParam', 'optionalParam must be a number').optional().isNumber();

Upvotes: 0

Related Questions