Created
December 17, 2019 11:20
-
-
Save arifmahmudrana/5419f0eb482862dc6ac78d4af9d45589 to your computer and use it in GitHub Desktop.
Joi conditional validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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