Last active
December 11, 2015 04:08
-
-
Save d1b1/4542410 to your computer and use it in GitHub Desktop.
Custom Node.js Validator - arrayOf(size, regex) - Provides the ability to validate that a request value is an array of a given size where each element matches the regex pattern provided. Uses underscore. Designed for a node.js API path where 'date=2012-11-01,2012-12-01' will be used for a date filter into Mongo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a custom validator that will ensure that | |
// the value is an array of two elements where each | |
// element matches the same regex format. | |
var _ = reqquire('underscore'); | |
var simpleDateRegex = new RegExp("^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])"); | |
Validator.prototype.arrayOf = function(size, regex) { | |
// Split the string into an array. | |
var opts = this.str.split(','); | |
// Check the size is correct. | |
if (opts.length != size ) { | |
this.error(this.msg + ', Missing Date values.'); | |
} | |
// Is the regex provides is a string, create a new RegExp | |
if (!regex instanceof RegExp) regex = new RegExp(regex); | |
// Use underscore to determine if which elements pass the regex. | |
var passed = _.filter(opts, function(o) { return regex.test(o) }); | |
// Generate an error is the expected and the passed do not match. | |
if (passed.length != opts.length) { | |
this.error(this.msg + ', One or more do not match format'); | |
} | |
return this; //Allow method chaining | |
} | |
/* | |
// Sample Usage: This is used in an express route to ensure that a query value will | |
// meet the required format pattern. Basically two YYYY-MM-DD, coma separted. | |
var v = new Validator(); | |
v.check(req.urlparams.date, 'Invalid Array of Dates (Requires: YYYY-MM-DD,YYYY-MM-DD)').arrayOf(2, simpleDateRegex); | |
if (v.getErrors().length > 0) { | |
res.send( JSON.stringify({ status: false, errors: v.getErrors()}), 200); | |
return; | |
} | |
*/ | |
// T: 1/15/2012 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment