From 1c0854987b3063e57289e04610067a5368d00252 Mon Sep 17 00:00:00 2001 From: Bermi Ferrer Date: Tue, 22 Oct 2013 06:35:29 +0200 Subject: [PATCH] Defaults should not override non object, array or string values. The method _.isEmpty() will return true for numeric values as well as for dates and booleans. The following patch (test case included) fixes that by using some extra logic for determining wether a value is empty or not. --- lib/rules.js | 21 ++++++++++++++++++++- test/default.js | 19 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/lib/rules.js b/lib/rules.js index 2868d02..b2554fa 100644 --- a/lib/rules.js +++ b/lib/rules.js @@ -30,7 +30,7 @@ Rules.prototype.Error = function(message, rule, value) { }; Rules.prototype.apply = function(value) { - if (_.isEmpty(value) && !_.isUndefined(this.rules['default'])) { + if (isValueEmpty(value) && !_.isUndefined(this.rules['default'])) { value = this.rules['default']; } @@ -250,6 +250,25 @@ var filters = { } }; +/** + * _.isEmpty(value) only verifies string arrays and objects. + * Other types will be asserted by a type verification. + * + * @param {mixed} value + * @return {Boolean} + */ +function isValueEmpty(value) { + if (_.isUndefined(value)) { + return true; + } + var canUseIsEmpty = _.isString(value) || _.isArray(value) || _.isObject(value) || false; + if (canUseIsEmpty) { + return _.isEmpty(value); + } + return (_.isNumber(value) || _.isBoolean(value) || _.isDate(value)) ? false : true; +} + + exports.create = function(param, rules) { return new Rules(param, rules); }; diff --git a/test/default.js b/test/default.js index e28cbab..1ea4b02 100644 --- a/test/default.js +++ b/test/default.js @@ -17,4 +17,23 @@ describe("default schemas", function() expect(input1.data.sound).to.equal("meow"); expect(input2.data.sound).to.equal("mooo"); }); + + it("respects non string/object/array values with defaults", function () { + var + input1, input2, + schema = schemajs.create({ + counter: { + type: 'number', + 'default': 30 + } + }); + + input1 = schema.validate({ + counter: 9 + }); + input2 = schema.validate({}); + + expect(input1.data.counter).to.equal(9); + expect(input2.data.counter).to.equal(30); + }); });