Validating a MongoDB object id

If you’re working with MongoDB then sooner or later you’re likely to hit an error when inserting or updating a document with a badly constructed Object Id.

For example:

  "_id": ObjectId("5289e30bcc93743934044d2Z",
  "name": "dvolr"

run in the Mongo shell will result in an “Error: invalid object id: not hex” message.

Of course, it’s better to catch this error before even attempting the database update.
This one line Javascript function uses a simple regular expression to check that the id is a 24-character hex string (i.e. only characters 0 to 9 and A to F). It will work in the browser and Node.js.

function isValidObjectID(str) {

  // A valid Object Id must be 24 hex characters
  return (/^[0-9a-fA-F]{24}$/).test(str);


// This one returns 'true'
alert( isValidObjectID('507f1f77bcf86cd799439011')

// This one returns false (notice the 'Z')
alert( isValidObjectID('507f1f77bcfZ6cd799439011')

I’ve also created a JSFiddle if you want to try it out with some other values.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s