New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Only allow fields that are defined. Deny other fields in body. #809
Comments
I can't find this feature too. There should be a way to remove/prevent extra fields UPDATE
|
@ammo8600 does @sergeytangyan's solution work for you? |
@gustavohenke I am thinking of adding support for passing |
I think the request from OP is doable if we can enhance the api validationResult(req, {strictParams: true}) // will generate errors if params is not in validation chain or checkSchema The tricky part would be that we need to check locations for And I think validationResult(req, {strictParams: ['body']} What do you think @gustavohenke |
Yeh, it serves the purpose. |
Works, but only with non array fields. Is there a workaround to also match array fields? Note: Solution works for non optional arrays. Optional arrays are neglected and full passed in data is returned from matchedData. |
Hey, I found a workaround with help of CoPilot. const Validator = (req, res, next) => {
const errors = validationResult(req);
const data = matchedData(req);
// Validate the required fields first.
if (!errors.isEmpty()) {
return res.status(422).send({
status: 'error',
errors: errors.array({ onlyFirstError: true, flatten: true }),
});
}
// If fields valid, then check unwanted fields.
if (Object.keys(data).length !== Object.keys(req.body).length) {
return res.status(400).send({
status: 'error',
message: 'Invalid request body.',
});
}
return next();
}; Yes, it's not that secure because it only checks the field length. At least it's better than nothing. |
@jaeger-dvlp but also your solution would not check deeper levels, e.g. if |
By the way everybody, I'm working on this for v7 right now 🙂 |
Hi hi, https://github.com/express-validator/express-validator/releases/tag/v7.0.0 is out with a fix for this 🙂 |
@gustavohenke I just here to say thank you, you are doing a beautiful job here. Br rules \o/ |
Is there a way to do this with request body schema? Docs dont seem to mention it. |
I am looking for something that only allows the fields defined in the chain, but return error on field that are not required.
Like if i require only body('username').exists() it should only accept username field, any other field may return an error.
Is there something i can do?
The text was updated successfully, but these errors were encountered: