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.
This commit is contained in:
Bermi Ferrer 2013-10-22 06:35:29 +02:00
parent f894df37be
commit 1c0854987b
2 changed files with 39 additions and 1 deletions

View File

@ -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);
};

View File

@ -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);
});
});