I’ve found a weird behavior when trying to check for a falsy value. I guess it is related to the parser across the HTTP. All values inserted (eg http://www.localhost:3000/knex/0) are converted into strings: falsy values like 0 or ” are converted into “0” and “”” respectively. Therefore, when trying to check for falsy values doesn’t raise an error.
May I be doing something wrong or is it something related to the library ?
My express-validator version: ^7.1.0
I left an example to test it:
const { body, validationResult, checkSchema, param } = require('express-validator');
const customChecker = (value) => {
console.log('ncustom');
console.log((value));
console.log(Boolean(value));
//if (value === 0) {console.log(value)}
if (value === '') {console.log(value)}
if (!Boolean(value)) {
throw new Error('Invalid id values. custom func');
} else {
return true;
}
}
const idSchema = {
id: {
//in: ['params'],
notEmpty:{errorMessage: "Not id provided"},
custom: { options: value => customChecker(value) },
//exists: { options: { values: 'falsy' } }
}
}
const validateId = [
// param('id').notEmpty().withMessage('ID is required'),
checkSchema(idSchema),
(req, res, next) => {
const VALRES = validationResult(req);
if (!VALRES.isEmpty()) {
return res.status(400).json({ errors: VALRES.array() });
}
next();
}
];
module.exports = { validateId };
app.get('/knex/:id',validateId, async (req, res) => {
try {
const item = await knex('tablename').where({ id: req.params.id });
res.json(item);
} catch (error) {
console.error('ERROR:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});