arb / celebrate

A joi validation middleware for Express.
MIT License
1.33k stars 66 forks source link

Set default value if validation is failed. especially for query params which are optional #226

Closed pnutmath closed 2 years ago

pnutmath commented 3 years ago

The 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?

arb commented 3 years ago

Joi has a .default() method available on every type. See this test for a code example.

pnutmath commented 3 years ago

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

arb commented 3 years ago

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.

pnutmath commented 3 years ago

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.

AdamAld commented 2 years ago

@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!

stale[bot] commented 2 years ago

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.