Last active
December 3, 2019 07:11
-
-
Save numToStr/c2cecff7e64d742019f416348d0df51c to your computer and use it in GitHub Desktop.
Mongodb/Mongoose ObjectId custom validation using @hapi/joi
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 { Types } = require("mongoose"); | |
const Joi = require("@hapi/joi"); | |
// custom validator | |
const customJoi = Joi.extend(joi => ({ | |
type: "objectId", | |
base: joi.string(), | |
messages: { | |
objectId: '"{{#label}}" must be a valid _id', | |
}, | |
validate(value, helpers) { | |
if (!Types.ObjectId.isValid(value)) { | |
return { value, errors: helpers.error("objectId") }; | |
} | |
return { value, errors: null }; | |
}, | |
})); | |
// Usage | |
const objectIDSchema = customJoi.objectId(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment