简体   繁体   English

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

[英]Joi validation when either of two values are present or missing

Have three parameters: latitude, longitude, zipcode有三个参数: latitude, longitude, zipcode

I need a joi validation that我需要一个joi 验证

  • requires latitude AND longitude when either is present OR zipcode is missing当存在或缺少邮政编码时需要纬度和经度
  • requires zipcode when EITHER latitude or longitude is missing.当缺少纬度或经度时需要邮政编码。

Something like this?像这样的东西?

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

I'm thinking there is a more elegant solution maybe usingobject.and()我想有一个更优雅的解决方案,也许使用object.and()

This solution may be useful:此解决方案可能有用:

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

You can validate multiple conditions in the following schema.您可以验证以下架构中的多个条件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM