admin管理员组文章数量:1391951
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
2 Answers
Reset to default 2You 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()
})
});
本文标签: javascriptJoi validation when either of two values are present or missingStack Overflow
版权声明:本文标题:javascript - Joi validation when either of two values are present or missing - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744695671a2620262.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论