I'm using express and express-validator in my Nodejs app. I want to check for the presence of at least one of incoming parameters. Its sort of either or combination.
Lets say my service accepts 2 parameters. I want to be sure at least one of them is provided by the client.
The below code would work for just one. But I have no idea how to make it either or.
req.checkBody('param1', 'Mandatory field param1 not populated').notEmpty();
check([field, message])Creates a validation chain for one or more fields. They may be located in any of the following request objects: req. body.
Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. On the other hand, express-validator uses validator. js to validate expressjs routes, and it's mainly built for express.
According to the express-validator documentation: . bail() is useful to prevent a custom validator that touches a database or external API from running when you know it will fail. Can be used multiple times IN THE SAME validation chain if needed.13-Feb-2020.
Say you want to update a model that has id
, status
, and content
... like a social media post, for example. Your controller may support updating the status
of the model or its content
. So, you could do something like the following:
export const updateModelValidation = [
param('id').exists().isNumeric(), // <-- required model identifier
oneOf( // <-- one of the following must exist
[
body('status').exists().isString(),
body('content').exists().isString(),
],
),
];
You could use multiple validation chains and use the oneOf function to validate against at least 1 validation chain.
https://www.npmjs.com/package/express-validator#oneofvalidationchains-message
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With