Daniel Stoyanoff
Daniel Stoyanoff

Reputation: 1564

Joi - not.exist()?

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!

Upvotes: 9

Views: 14665

Answers (2)

Thiha Thit
Thiha Thit

Reputation: 191

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

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

Upvotes: 14

Ankh
Ankh

Reputation: 5718

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]

Upvotes: 11

Related Questions