How can you base a Joi `when` condition on a value from the context?

3.5k Views Asked by At

Joi's ref documentation suggests that a Reference created using Joi.ref can refer to a value from the context object. Joi's any.when documentation suggests that the condition parameter accepts a Reference. However, I can't get the following simple usage to work:

import Joi from "joi";

const schema = Joi.object({
  year: Joi.number().when(Joi.ref(`$flag`), {
    is: Joi.boolean().truthy,
    then: Joi.number().min(2000),
  }),
});

const value = {
  year: 1999,
};

const context = {
  flag: true
};

const result = schema.validate(value, { context });

This code results in a passing validation. However, I would expect it to fail. What am I missing?

1

There are 1 best solutions below

2
On BEST ANSWER

You need to use boolean().valid(true) so only the boolean value true passes!

boolean().truthy() accepts a list of additional values to be considered valid booleans. E.g. boolean().truthy('YES', 'Y'). Details in the Documentation

joi version: 17.2.1

const Joi = require('joi');

const schema = Joi.object({
  year: Joi.number().when(
    Joi.ref('$flag'), {
      is: Joi.boolean().valid(true), then: Joi.number().min(2000),
    },
  ),
});

const value = {
  year: 1999,
};

// fails
const context = {
  flag: true
};

// passes
const context = {
  flag: false
};

const result = schema.validate(value, { context });
console.log(result.error);