Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 928
Daniel Stoyanoff Avatar asked Nov 13 '18 09:11

Daniel Stoyanoff


2 Answers

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]

like image 140
Ankh Avatar answered Nov 19 '22 00:11

Ankh


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

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

like image 12
Thiha Thit Avatar answered Nov 18 '22 23:11

Thiha Thit