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

Joi validation when either of two values are present or missing

本文关键字:任何一 验证 Joi 两个 存在      更新时间:2023-09-26

有三个参数:latitude, longitude, zipcode

我需要一个joi验证

  • 需要纬度和经度,当其中一个存在或邮编缺失
  • 当纬度或经度缺失时,
  • 要求邮政编码。

像这样?

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

您可以在以下模式中验证多个条件。

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

这个解决方案可能有用:

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