Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

This is a small addition that enables default attribute #154

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
24 changes: 24 additions & 0 deletions test/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down