diff --git a/index.js b/index.js index 8ec89af..e67d30c 100644 --- a/index.js +++ b/index.js @@ -66,6 +66,9 @@ Anchor.prototype.to = function (ruleset, context) { if (rule === 'type') { + if (typeof ruleset['in'] === 'object' && ruleset['in'].hasOwnProperty(this.data)) { + this.data = ruleset['in'][this.data] + } // Use deep match to descend into the collection and verify each item and/or key // Stop at default maxDepth (50) to prevent infinite loops in self-associations errors = errors.concat(Anchor.match.type.call(context, this.data, ruleset['type'])); diff --git a/lib/match/rules.js b/lib/match/rules.js index 459c880..be739dd 100644 --- a/lib/match/rules.js +++ b/lib/match/rules.js @@ -5,6 +5,30 @@ var _ = require('lodash'); var validator = require('validator'); +//the validator author reject this PR, so override here: +validator.isIn = function (str, options) { + var i ,result=false; + if (Object.prototype.toString.call(options) === '[object Array]') { + var array = []; + for (i in options) { + array[i] = validator.toString(options[i]); + } + result = array.indexOf(str) >= 0; + } else if (typeof options === 'object') { + if (options.hasOwnProperty(str)) { + result = true; + } else for (i in options) { + if (str == validator.toString(options[i])) { + result = true; + break; + } + } + } else if (options && typeof options.indexOf === 'function') { + result = options.indexOf(str) >= 0; + } + return result; +}; + /** diff --git a/test/basicType.test.js b/test/basicType.test.js index fec4c55..ab7eea6 100644 --- a/test/basicType.test.js +++ b/test/basicType.test.js @@ -83,6 +83,14 @@ describe('basic rules', function() { it ('"number" should identify integers ', function () { return testType('number',28235,'foo'); }); + + it ('"number" should support the enum(in) ', function () { + return testType({type: 'number', 'in': {one:1, two:2}},'one','foo', true); + }); + + it ('"number" should support the enum(in) and pass value directly', function () { + return testType({type: 'number', 'in': {one:1, two:2}}, 1, 'foo', true); + }); }); }); diff --git a/test/util/testType.js b/test/util/testType.js index ec69afa..32295be 100644 --- a/test/util/testType.js +++ b/test/util/testType.js @@ -4,21 +4,19 @@ var async = require('async'); // Test a rule given a deliberate example and nonexample // Test WITH and WITHOUT callback -module.exports = function testType (rule, example, nonexample) { +module.exports = function testType (rule, example, nonexample, isRule) { // Throw an error if there's any trouble // (not a good production usage pattern-- just here for testing) var exampleOutcome, nonexampleOutcome; + if (isRule !== true) + rule = {type: rule}; // Should be falsy - exampleOutcome = anchor(example).to({ - type: rule - }); + exampleOutcome = anchor(example).to(rule); // Should be an array - nonexampleOutcome = anchor(nonexample).to({ - type: rule - }); + nonexampleOutcome = anchor(nonexample).to(rule); if (exampleOutcome) { return gotErrors(exampleOutcome);