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

时间:2016-10-27 22:27:52

标签: joi

有三个参数:latitude, longitude, zipcode

我需要一个joi validation

    当存在或缺少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() })
});

我认为使用object.and()

可能会有更优雅的解决方案

2 个答案:

答案 0 :(得分:0)

此解决方案可能很有用:

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()
    })
});

答案 1 :(得分:0)

您可以在以下架构中验证多个条件。

    const schema = Joi.object().keys({
        searchby: Joi.string().valid('phone', '_id', 'cno').required(), // field name
        searchvalue: Joi
            .when('searchby', { is: "phone", then: Joi.string().regex(/^(923)\d{9}$/, 'numbers').max(12).min(12).required() })
            .when('searchby', { is: "_id", then: Joi.objectId().required() })
            .when('searchby', { is: "nic", then: Joi.number().required() })
    });
相关问题