【问题标题】:NodeJS Joi Validation: Require either two fields or a third oneNodeJS Joi 验证:需要两个字段或第三个字段
【发布时间】:2022-03-02 17:14:42
【问题描述】:

我想允许 API 调用者通过Geohash 或普通geo coordinates 输入地理数据。我的 Joi 验证架构目前如下所示:

const schema = Joi.object({

        geoHash: Joi.string(),
        lat: Joi.number().precision(8),
        lon: Joi.number().precision(8),
    });

那么我如何要求 geohash 或 lat 和 lon 的组合?验证后如何知道使用了这两个选项中的哪一个?

【问题讨论】:

    标签: node.js validation joi


    【解决方案1】:

    架构验证需要结合 geoHash 或 lat + lon:

    const schema = Joi.object({
        geoHash: Joi.string(),
        lat: Joi.number().precision(8),
        lon: Joi
            .number()
            .precision(8)
            .when('lat', {
                not: undefined,
                then: Joi.required(),
            })
    }).or('geoHash', 'lat');
    

    我不确定我们是否可以找到使用了哪个验证。我查看了文档,但找不到任何文档。

    你可以有一个简单的Js代码:

    const isGeoHashUsed = !!req.query.geoHash // assuming it's a GET request
    

    如果为真,则使用 geoHash。否则,使用 lat + lon。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多