Juan enriquez
Juan enriquez

Reputation: 173

Joi - how to check when other key's value is null/empty

I am having trouble trying to validate a JSON file, to be more specific I am having trouble with a when condition.

I have a a key that has to be a past date, and isn't required. Then I have a b key that should be an url and if a is null/empty, b can be empty, otherwise must be required.

I'll leave my code below to make it clear, but right now I'm not getting any error if b is null but a isn't.

a: Joi.date().less("now").raw().optional().allow(null, ""),
b: Joi.string()
  .uri({ scheme: [/https?/] })
  .when("a", {
    is: Joi.any().empty(),
    then: Joi.optional().allow(null, ""),
    otherwise: Joi.required(),
  }),

Upvotes: 7

Views: 8055

Answers (1)

Juan enriquez
Juan enriquez

Reputation: 173

Found the solution, my is condition was wrong.

Instead of using is: Joi.any().empty() I put is: Joi.any().valid(null, "") and it worked.

So the solution is this:

a: Joi.date().less("now").raw().optional().allow(null, ""),
b: Joi.string()
  .uri({ scheme: [/https?/] })
  .when("a", {
    is: Joi.any().valid(null, ""),
    then: Joi.optional().allow(null, ""),
    otherwise: Joi.required(),
  }),

Upvotes: 9

Related Questions