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".
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.
What worked for me was using req.checkBody('optionalParam', 'optionalParam must be a number').optional().isNumber();
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'),
])