当两个值中的任何一个存在或缺失时的 Joi 验证

Sco*_*ott 5 javascript validation joi

有三个参数: latitude, longitude, zipcode

我需要一个穰验证

  • 当存在或缺少邮政编码时需要纬度和经度
  • 当缺少纬度或经度时需要邮政编码。

像这样的东西?

Joi.object().keys({
    latitude: Joi.number().when('zipcode', { is: undefined, then: Joi.required() }),
    longitude: Joi.number().when('zipcode', { is: undefined, then: Joi.required() }),
    zipcode: Joi.number().when(['latitude', 'longitude'], { is: undefined, then: Joi.required() })
});
Run Code Online (Sandbox Code Playgroud)

我想有一个更优雅的解决方案,也许使用object.and()

Sae*_*adi 1

这个解决方案可能有用:

schema = Joi.object().keys({
  location: Joi.object().keys({
    lat: Joi.number(),
    long: Joi.number()
  }).and('lat', 'long'),
  timezone: Joi.alternatives()
    .when('location', {
        is: null,
        then: Joi.number().required(),
        otherwise: Joi.number()
    })
});
Run Code Online (Sandbox Code Playgroud)

  • 但该解决方案仅在您更改数据结构时才有效。 (2认同)