Skip to content

Instantly share code, notes, and snippets.

@numToStr
Last active December 3, 2019 07:11
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 numToStr/c2cecff7e64d742019f416348d0df51c to your computer and use it in GitHub Desktop.
Save numToStr/c2cecff7e64d742019f416348d0df51c to your computer and use it in GitHub Desktop.
Mongodb/Mongoose ObjectId custom validation using @hapi/joi
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