Skip to content

Instantly share code, notes, and snippets.

@d1b1
Last active December 11, 2015 04:08
Show Gist options
  • Save d1b1/4542603 to your computer and use it in GitHub Desktop.
Save d1b1/4542603 to your computer and use it in GitHub Desktop.
Custom Node.js Validator for MongoIDs. Build to DRY out and standardize the validation of MongoIDs passed as path or query values into a express endpoint.
var Validator = require('validator').Validator;
Validator.prototype.isObjectID = function() {
var regex = new RegExp("^[0-9a-fA-F]{24}$");
if (!regex.test(this.str)) {
this.error(this.msg + ', Requires a String of 12 bytes or a string of 24 hex characters.');
}
return this; //Allow method chaining
}
/*
var v = new Validator();
v.check(req.params.ucs, 'Invalid Mongo Object ID.').isObjectID();
if (v.getErrors().length > 0) {
res.send( JSON.stringify({ status: false, errors: v.getErrors()}), 200);
return;
}
*/
// T: 1/17/2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment