javascript - Joi validation when either of two values are present or missing - Stack Overflow

Have three parameters: latitude, longitude, zipcodeI need a joi validation thatrequires latitude AND lo

Have three parameters: latitude, longitude, zipcode

I need a joi validation that

  • 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 using object.and()

Have three parameters: latitude, longitude, zipcode

I need a joi validation that

  • 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 using object.and()

Share Improve this question edited Oct 21, 2020 at 13:22 frederj 1,7351 gold badge11 silver badges20 bronze badges asked Oct 27, 2016 at 22:27 ScottScott 9482 gold badges13 silver badges25 bronze badges 2
  • Did you get any solution? – Ashish Commented Nov 23, 2016 at 9:10
  • Nope. I used a hack which somewhat serves my purpose in that it won't allow values I don't want but the error messages are confusing. – Scott Commented Nov 30, 2016 at 23:23
Add a ment  | 

2 Answers 2

Reset to default 2

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744695671a4588476.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信