Skip to content

Instantly share code, notes, and snippets.

@arifmahmudrana
Created December 17, 2019 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arifmahmudrana/5419f0eb482862dc6ac78d4af9d45589 to your computer and use it in GitHub Desktop.
Save arifmahmudrana/5419f0eb482862dc6ac78d4af9d45589 to your computer and use it in GitHub Desktop.
Joi conditional validation
const joi = require("joi");
// const schema = joi.object({
// roomIds: joi.array()
// .required()
// .min(1)
// .max(6)
// .sparse()
// .items(joi.string())
// }).keys({
// searchCode: joi.string()
// .when("$roomSearchCode", {
// is: joi.boolean()
// .valid(false)
// .required(),
// then: joi.required(),
// otherwise: joi.optional()
// }),
// hotelId: joi.string()
// .when("$roomSearchCode", {
// is: joi.boolean()
// .valid(false)
// .required(),
// then: joi.required(),
// otherwise: joi.optional()
// }),
// roomSearchCode: joi.string()
// .when("$roomSearchCode", {
// is: joi.boolean()
// .valid(true)
// .required(),
// then: joi.required(),
// otherwise: joi.optional()
// })
// });
const schema = joi.object({
roomIds: joi.array()
.required()
.min(1)
.max(6)
.sparse()
.items(joi.string()),
searchCode: joi.string()
.when("$roomSearchCode", {
is: joi.boolean()
.valid(false)
.required(),
then: joi.required(),
otherwise: joi.optional()
}),
hotelId: joi.string()
.when("$roomSearchCode", {
is: joi.boolean()
.valid(false)
.required(),
then: joi.required(),
otherwise: joi.optional()
}),
roomSearchCode: joi.string()
.when("$roomSearchCode", {
is: joi.boolean()
.valid(true)
.required(),
then: joi.required(),
otherwise: joi.optional()
})
});
const body = {
roomIds: ["1"],
searchCode: "dasdasd",
roomSearchCode: "dasdasd",
hotelId: "adasdas"
}
// const body = {
// roomIds: ["1"],
// roomSearchCode: null
// }
// const body = {
// roomIds: ["1"]
// }
const validationResult = joi.validate(
body,
schema,
{ context: { roomSearchCode: Object.prototype.hasOwnProperty.call(body, "roomSearchCode") } }
);
console.log(validationResult);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment