arb / celebrate

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

Question: how to extend Joi with a validator that needs to read request's headers #128

Closed ctessier closed 5 years ago

ctessier commented 5 years ago

Hi,

I need to extend Joi with a custom type validator that would validate a JSON body property. Although, in order to be able to validate this value, I need a custom request header that is also being sent in the request.

I seem to not be able to access the request object in the rule of my validator. Can you think of any other possibility to do that? Maybe a way to define a peer dependency between a JSON body property and a header?

Thank you very much for your help. Regards

ctessier commented 5 years ago

Seems like reqContext could do the trick for me. Will try it out.. If you have an example so long, I'll take it :)

Thanks

arb commented 5 years ago

That test shows you how you can use reqContext: https://github.com/arb/celebrate/blob/master/test/celebrate.test.js#L236-L261

Om4ar commented 5 years ago

@arb still is it possible to inject an extended joi , can you elaborate more on that if it is possible ?

the question is why it is not done like this "to be injected"

i think this is a limitation for me too

arb commented 5 years ago

@MuhamadOmr in the future, please open new issues when you have questions that deviate from the original post...

That being said, this test shows how you can work with an extended Joi.

ctessier commented 5 years ago

Thanks @arb, reqContext did the trick. I could then simply use options.context.headers.MY_HEADER in the rules's validate method of my Joi extension 👍 The example with the query param is very interesting too!