"default" keyword in "items" subschemas, #42

master
Evgeny Poberezkin 2016-01-09 01:37:45 +00:00
parent 0b725bbc31
commit d7dd660d25
2 changed files with 39 additions and 6 deletions

View File

@ -43,7 +43,16 @@ var {{=$valid}};
{{# def.elseIfValid}}
{{?}}
{{ var $useDefaults = it.opts.useDefaults && !it.compositeRule; }}
{{~ $schema:$sch:$i }}
{{ var $passData = $data + '[' + $i + ']'; }}
{{? $useDefaults && $sch.default !== undefined }}
if ({{=$passData}} === undefined)
{{=$passData}} = {{= it.useDefault($sch.default) }};
{{?}}
{{? {{# def.nonEmptySchema:$sch }} }}
valid{{=$it.level}} = true;
@ -53,7 +62,6 @@ var {{=$valid}};
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
$it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
var $passData = $data + '[' + $i + ']';
if (it.opts.v5) $it.dataPathArr[$dataNxt] = $i;
}}

View File

@ -360,12 +360,7 @@ describe('Ajv Options', function () {
var validate = ajv.compile(schema);
var data = {};
try {
validate(data) .should.equal(true);
} catch(e) {
console.log('failed with:', ajv.opts);
throw e;
}
data. should.eql({ foo: 'abc', bar: 1, baz: false, nil: null, obj: {}, arr:[] });
var data = { foo: 'foo', bar: 2, obj: { test: true } };
@ -373,5 +368,35 @@ describe('Ajv Options', function () {
data. should.eql({ foo: 'foo', bar: 2, baz: false, nil: null, obj: { test: true }, arr:[] });
}
});
it('should replace undefined item with default value', function() {
test(Ajv({ useDefaults: true }));
test(Ajv({ useDefaults: true, allErrors: true }));
function test(ajv) {
var schema = {
items: [
{ type: 'string', default: 'abc' },
{ type: 'number', default: 1 },
{ type: 'boolean' }
]
};
var validate = ajv.compile(schema);
var data = [];
validate(data) .should.equal(true);
data. should.eql([ 'abc', 1 ]);
var data = [,,true];
validate(data) .should.equal(true);
data. should.eql([ 'abc', 1, true ]);
var data = ['foo',,'false'];
validate(data) .should.equal(false);
validate.errors .should.have.length(1);
data. should.eql([ 'foo', 1, 'false' ]);
}
});
});
});