No method for validating existence of property in req.params, req.body, or req.query
See original GitHub issueSuppose I have a route expecting to receive the parameter req.body.heading
. If this parameter exists and was sent by the client, then my validation will run as expected. I will check req.validationErrors()
and proceed accordingly. However, if req.body.heading
was not sent by the client, its value will be undefined
. Based on my limited testing, when this happens, the undefined
value will be coerced to an empty string and validation will proceed on that empty string. A validator deprecated
message also gets printed to the console, and I understand this is going to be addressed in the future. However, the problem here is that there is currently no way to check if a value is undefined
and produce an error when it is undefined
. Currently, the undefined
value gets coerced to an empty string and validated as an empty string.
This is problematic because there is a big difference between not receiving a value from the client and receiving an empty string. These constitute independent cases that one may wish to handle differently. In my case, I consider receiving no value (i.e. undefined
) as an error, whereas receiving an empty string may or may not be valid depending on the context.
My solution has been to create a custom validator to check if the value exists:
customValidators: {
exists: value => value !== undefined,
}
This achieves the desired behavior whereby if the value is undefined
, an error will be produced in req.validationErrors()
. In practice, I also use the optional()
method immediately after exists()
to stop any further validation when the value is undefined
.
Typical usage would look something like this:
req.checkBody('heading').exists().optional()...;
With that in mind, I’d appreciate some feedback on whether or not this is the best way to address this issue. Likewise, if this makes sense and doesn’t conflict with any upgrade plans, I’d like to make a PR to add an exists()
method. In this PR I would go ahead and bundle the optional()
behavior into the exists()
method since using it without that behavior doesn’t really make sense. Though I would add an option to allow exists()
to be used without the optional()
behavior.
Issue Analytics
- State:
- Created 7 years ago
- Comments:6 (3 by maintainers)
Hello folks, v4.0.0 has finally been released.
It brings support for a new validator called
.exists()
, which you can see some example of how to use here: https://github.com/ctavan/express-validator/issues/382#issuecomment-325174919Don’t forget to check the README for complete docs and the upgrade guide for version 3 users.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.