9

I am trying to do a validation with Joi, but I came to a scenario that I cannot achieve. I have an object. In some cases, the object will have an id (edit) and on the others it will not (create).

I want to validate that in case "id" is not present, few other fields should be there.

So far my only solution that works is when id is null and not missing at all. Is there a way to match non-existing key or should I change it to null (a bit hacky).

joi.object().keys({
  id: joi
    .number()
    .min(0)
    .allow(null),
  someOtherField1: joi.when("id", { is: null, then: joi.required() })
});

Thank you in advance!

soorapadman
  • 4,451
  • 7
  • 35
  • 47
Daniel Stoyanoff
  • 1,443
  • 1
  • 9
  • 25

2 Answers2

13

Undefined is the empty value for Joi. Use "not" instead of "is"

Example: { not: Joi.exist(), then: Joi.required() }

Thiha Thit
  • 181
  • 2
  • 2
11

If you're prepared to accept null as an id and would like to perform conditionals on it I'd suggest defaulting the id field to null. This way you can omit it from the payload and still query it using Joi.when().

For example:

Joi.object().keys({
    id: Joi.number().min(0).allow(null).default(null),
    someOtherField1: Joi.string().when('id', { is: null, then: Joi.required() })
});

Passing both an empty object, {}, and an object with a null id, { "id": null }, will result in:

ValidationError: child "someOtherField1" fails because ["someOtherField1" is required]

Ankh
  • 5,478
  • 3
  • 36
  • 40
  • @Ankh what if I want to check if multiple properties exist? Can we write a thing like the following one? `Joi.string().when('id'||'guid', { is: null, then: ...` – srgbnd Jan 28 '19 at 11:24
  • 1
    @srgbnd the `.when()` call can be chained e.g. `.when({ ... }).when({ ... })...` – Ankh Jan 28 '19 at 11:30