Search code examples
javascripttypescriptjoi

How to validate sum of refs in Joi


How can I validate the total of two refs as below? I would prefer have custom be on the total, yet unsure of how to get the value of the refs in the custom when using Joi.ref.

I can do the following and hang a custom off the entire validation schema, but would prefer to attach it to total.

I don't want to use expression()

I prefer not to change the schema structure as per this answer.

  const widgetValidator = Joi.object({
    a: Joi.number().integer().min(0).required(),
    b: Joi.number().integer().min(1).required(),
    total: Joi.number().integer().min(1).required(),
  }).custom((value: {a: number; b: number; total: number;}, helpers) => {
      if (value.total !== value.a + value.b) {
        throw new Error('invalid balance calculation');
      }

      return value;
    },
  );

Solution

  • When you install custom on an attribute, it will be a little hard to get whole object values. You have to get it from helpers's states:

    Joi.object({
        a: Joi.number().integer().min(0).required(),
        b: Joi.number().integer().min(1).required(),
        total: Joi.number().integer().min(1).required().custom((value, helpers) => {
          const { a, b } = helpers.state.ancestors[0];
          if (value !== a + b) {
            throw new Error('invalid balance calculation');
          }
    
          return value;
        },
      )
    })