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