当条件时 Joi 循环依赖错误

Dmy*_*sak 2 validation circular-dependency node.js joi

我有 3 个查询参数经度纬度半径

我有 3 个可能的条件:

  • 半径- 空,经度纬度,有一些值
  • 所有 3 个参数都有值
  • 所有 3 个参数为空

在所有其他情况下发送验证错误。

例如

经度=3.12 - 错误

纬度=2.12,半径=3.2 - 误差

经度=12.12,纬度=2.12 - 好的

我的架构看起来像这样:

const schema = Joi.object().keys({
    longitude: Joi.number().optional().error(new Error('LBL_BAD_LONGITUDE'))
      .when('latitude', { is: Joi.exist(), then: Joi.number().required() })
      .when('radius', { is: Joi.exist(), then: Joi.number().required() }),
    latitude: Joi.number().optional().error(new Error('LBL_BAD_LATITUDE'))
      .when('longitude', { is: Joi.exist(), then: Joi.number().required() })
      .when('radius', { is: Joi.exist(), then: Joi.number().required() }),
    radius: Joi.number().optional().error(new Error('LBL_BAD_RADIUS')),
  });
Run Code Online (Sandbox Code Playgroud)

结果我得到错误

AssertionError [ERR_ASSERTION]: item added into group latitude created a dependencies error
Run Code Online (Sandbox Code Playgroud)

知道如何验证这 3 个参数吗?

Ank*_*nkh 5

你离你不远了……这里的诀窍是满足你的longitude and latitude with some value要求。

Joi.object().keys({
    radius: Joi.number(),
    latitude: Joi.number().when('radius', { is: Joi.exist(), then: Joi.required() }),
    longitude: Joi.number().when('radius', { is: Joi.exist(), then: Joi.required() })
}).and('latitude', 'longitude');
Run Code Online (Sandbox Code Playgroud)

所述.and()改性剂产生之间的对依赖性latitudelongitude; 如果其中一个存在,那么另一个也必须存在。然而,省略这两个键也是有效的,因为它们都不是严格要求的(有助于all 3 parameters empty)。

通过使用.and()我们只需要.when()根据是否radius存在添加修改。

只有以下有效负载格式有效:

{
    latitude: 1.1,
    longitude: 2.2,
    radius: 3
}

{
    latitude: 1.1,
    longitude: 2.2
}

{}
Run Code Online (Sandbox Code Playgroud)