Closed pnutmath closed 2 years ago
Joi has a .default()
method available on every type. See this test for a code example.
Consider below scenario:
page: Joi.object().keys({
page: Joi.number().min(1).default(1),
limit: Joi.number().min(1).default(10),
}),
here, in case my request is like /?page=&limit=0
then page failed because it considered as string and limit failed because of min criteria.
As query params are optional, I am interested to set default value even after validation fails, without rejecting request. I don't think its happening right now
It's rejecting because the schema says that limit
minimum is 1, but it's being set to 0 so the request is invalid. celebrate
doesn't apply the transformations unless the request passes validation.
If you make limit
2, then it should pass and page
should default to 1.
Yes understood @arb, but I am saying like even though it fails validation for query params and if we have set default then validation should pass with default value.
I am suggesting this for query params only.
@pnutmath Your suggestion breaks standard validation for optional keys in the schema.. A possible workaround could be to use the .when(..)
functionality on the schema itself to mutate the validation of that field (any().when(..)
Docs), or using any of their Alternative helpers (alternatives.conditional|match|try(..)
Docs).
Hope this helps!
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.
node
version - v12.22.1celebrate
version - 15.0.0joi
version (vianpm ls --depth=0 | grep joi
) - NAThe issue I am having with
celebrate
is:Set default value if validation is failed. especially for query params which are optional. Can we support this?