How to force joi to invoke custom function when the object schema is invalid?

Viewed 167

I create in my Joi schema a custom function to validate if name is equal to confirmName.

And I use abortEarly: false to get all the errors.

The problem is the when validation failed in the object the custom function not invoke.

currently the results output is just for birthYear. it should be birthYear and custom .

Is there a way to make it work as I describe?

{ name: "foo", confirmName: "oo", birthYear: 0 },

codesandbox.io

const Joi = require("joi");

console.clear();

const schema = Joi.object({
  name: Joi.string(),
  confirmName: Joi.string(),
  birthYear: Joi.number().integer().min(1900).max(2013)
}).custom((doc, helpers) => {
  const { name, confirmName } = doc;
  if (name !== confirmName) {
    throw new Error("name not match!!");
  }
});

const { error } = schema.validate(
  { name: "foo", confirmName: "oo", birthYear: 0 },
  { allowUnknown: true, abortEarly: false }
);

console.log({ error });

if (error) {
  const { details } = error;
  console.log({ details });
}
1 Answers

You don't need a custom validation to make sure name is equal to confirmName.

Just use a reference to the value:

const schema = Joi.object({
  name: Joi.string(),
  confirmName: Joi.ref('name'),
  birthYear: Joi.number().integer().min(1900).max(2013)
});

And if you want to override the error message, you can use .messages:

confirmName: Joi.string().required()
                         .valid(Joi.ref('name'))
                         .messages({'any.only': 'name not match!!'})
Related