diff --git a/lib/validator.js b/lib/validator.js index 2f3ef63..9aaa276 100644 --- a/lib/validator.js +++ b/lib/validator.js @@ -205,6 +205,11 @@ Validator.prototype.validateSchema = function validateSchema (instance, schema, return this.validateSchema(instance, resolved.subschema, options, subctx); } + // Set default value if instance is undefined and default is defined + if(options.setDefaults && typeof instance === 'undefined' && schema.required !== true) { + result.instance = instance = schema.default; + } + var skipAttributes = options && options.skipAttributes || []; // Validate each schema attribute against the instance for (var key in schema) { diff --git a/test/attributes.js b/test/attributes.js index b29154b..093395c 100644 --- a/test/attributes.js +++ b/test/attributes.js @@ -295,6 +295,30 @@ describe('Attributes', function () { return this.validator.validate({'the_field':'bar'}, {'type': 'object', 'properties':{'the_field': {'enum': ['foo', 'bar', 'baz'], 'required': true}}}).valid.should.be.true; }); }); + + describe('default', function () { + beforeEach(function () { + this.validator = new Validator(); + }); + + it('should preserve value if field is defined', function () { + var validation = this.validator.validate({'the_field': 'foo'}, {'type': 'object', 'properties':{'the_field':{'type': 'string', 'default': 'bar'}}}, {setDefaults: true}); + validation.valid.should.be.true; + validation.instance.the_field.should.equal('foo'); + }); + + it('should not set default value even field is undefined if options.setDefaults is not true', function () { + var validation = this.validator.validate({}, {'type': 'object', 'properties':{'the_field':{'type': 'string', 'default': 'bar'}}}); + validation.valid.should.be.true; + validation.instance.should.not.have.property('the_field'); + }); + + it('should set default value if field is undefined and options.setDefaults is true', function () { + var validation = this.validator.validate({}, {'type': 'object', 'properties':{'the_field':{'type': 'string', 'default': 'bar'}}}, {setDefaults: true}) + validation.valid.should.be.true; + validation.instance.the_field.should.equal('bar'); + }); + }); describe('description', function () { beforeEach(function () {