how to access another field inside custom function in joi?

Viewed 916

I using Joi to validate my input against the schema.

How to access the foo value inside custom function?

codesandbox.io

import * as Joi from "joi";

console.clear();

const schema = Joi.object({
  bar: Joi.string().custom((x) => {
    // how to access foo value?

    console.log({ x });
  }),
  foo: Joi.string()
});

schema
  .validateAsync({ foo: "myfoo", bar: "mybar" })
  .then((x) => {
    console.log({ x });
  })
  .catch((err) => {
    console.log({ err });
  });
1 Answers

If you want to access some other key you need to add the custom validation to the object:

const schema = Joi.object({
  bar: Joi.string(),
  foo: Joi.string()
}).custom((obj, helpers) => {
  // you have access to the full object above.
  const { foo, bar } = obj;

  if (foo === "myfoo") {

  }
});
Related