最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Joi - not.exist()? - Stack Overflow

programmeradmin3浏览0评论

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!

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!

Share Improve this question edited Nov 13, 2018 at 9:51 soorapadman 4,5097 gold badges37 silver badges48 bronze badges asked Nov 13, 2018 at 9:47 Daniel StoyanoffDaniel Stoyanoff 1,5641 gold badge11 silver badges28 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

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

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

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]

发布评论

评论列表(0)

  1. 暂无评论