Skip to content

Instantly share code, notes, and snippets.

@erkobridee
Last active November 10, 2021 15:31
Show Gist options
  • Save erkobridee/e1073ce7841eb5fc4425a934e8b578ab to your computer and use it in GitHub Desktop.
Save erkobridee/e1073ce7841eb5fc4425a934e8b578ab to your computer and use it in GitHub Desktop.
/*
useful references
regex pattern
https://github.com/mongodb/js-bson/blob/v4.2.0/src/objectid.ts#L9
validation function
https://github.com/mongodb/js-bson/blob/v4.2.0/src/objectid.ts#L301
/^([a-zA-Z0-9]{24}|[a-zA-Z0-9]{12})$/
https://jex.im/regulex/#!flags=&re=%5E(%5Ba-zA-Z0-9%5D%7B24%7D%7C%5Ba-zA-Z0-9%5D%7B12%7D)%24
*/
function isValidObjectID(str) {
// coerce to string so the function can be generically used to test both strings and native objectIds created by the driver
str = str + '';
var len = str.length, valid = false;
if (len == 12 || len == 24) {
valid = /^[a-zA-Z0-9]+$/.test(str);
}
return valid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment