arb / celebrate

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

Access req.body object when validating #202

Closed papidb closed 3 years ago

papidb commented 3 years ago

My joi schema looks like this:

import phone from 'phone'

const phoneMethodValidator = (value, helpers) => {
//  I need to get the value for the countryCode in req.body
  let values = phone(value, "NGA");
  if (values.length !== 2) {
    throw new Error("phone isn't valid");
  }
  return value;
};
`
`[Segments.BODY]: Joi.object().keys({
      countryCode: Joi.string().allow(null),
      phone: Joi.string()
        .custom(phoneMethodValidator, "phone validation")
        .required()
})

Here is an example value that is not working as expected:

{phone: "08000000000", countryCode: "NGA" }

The issue I am having with celebrate is: I need access to the value of countryCode in req.body, and Joi.ref isn't doing any justice

I need the value of countryCode so I can use it to do custom validation of the phone number provided. Thanks

arb commented 3 years ago

Trying taking a look at this test that uses the request context during validation. That might help you achieve what you're trying to do. I'm not 100% sure though since the .custom method is a little limited with what all it's going to receive as arguments. Make sure you check out everything available in helpers to see if there is anything useful there.

papidb commented 3 years ago

Thanks but looking into helpers helped a lot(got help from a friend).

helpers.state.ancestors[0] // gives the full object