I'm building an API in express and I have a few routes. I am also using express-validator
to validate what the client sends. This gives an error if the client sends the right keys and the values for those keys fail the validation defined from the express-validator
schema.
However, the issue I'm having now, is that I can't really check whether the client is sending a random key.
Here's an illustration. API can accept the following:
{
"firstName": "John",
"lastName": "Doe",
"email": "johndoe@example.com"
}
Validator will check if firstName
, lastName
, and email
are valid and accept the data.
Now let's say I send the following:
{
"firstName": "John",
"lastName": "Doe"
}
This also works because the validator only requires firstName
and lastName
. email
is optional, so it still goes through.
Now, let's try something else:
{
"firstName": "234839248923",
"lastName": "Doe",
"email": "johndoe@gmail.com"
}
In the above, the validation fails, and we get an error because firstName
can't be just numbers.
So far, so good.
Now, here's another case:
{
"firstName": "John",
"lastName": "Doe",
"email": "johndoe@gmail.com",
"randomKeyIDontNeed": "I don't need this"
}
The above works perfectly and goes through, even though there is the randomKeyIDontNeed
which is sent from the client.
I can't find a way with express-validator
to check if random keys are sent and give an error.
Is there a way to check that only those 3 keys are allowed, whether required or optional, and give the client an error if they send the wrong keys?
Here's one way I am thinking of doing it, but I'm not sure if that makes sense:
- Have an array of keys which are allowed. e.g
arr = ["firstName,"lastName", "email"]
- Get all the keys from
req.body
.- Check if keys from
req.body
are in arrayarr
. If not, return an error.
Is there a simpler, cleaner way of doing this?
Right now, whenever a random key is sent, it's not being used in the back-end and it doesn't really affect anything. So, is there even a point to validate the random keys?
What are the repercussions of not doing the validation for the random keys?
You may want to look into using express-joi-validation. It does validation on types for the given keys, and prevents the user from passing other values.
Here is a file I have for my validators for some Stripe routes
const Joi = require('joi');
exports.postPaymentMethod = Joi.object({
paymentMethodId: Joi.string().required()
});
exports.deletePaymentMethod = Joi.object({
paymentMethodId: Joi.string().required()
});
And here is how I use them.
const validator = require('express-joi-validation').createValidator({});
router.delete('/payment-methods', validator.body(deletePaymentMethod), ash(async (req, res) => {
// validated body is passed here, safe to use w/o lots of error checking
var paymentMethodId = req.body.paymentMethodId;
}));