Skip to content

Commit

Permalink
fix: removeAdditional option breaking custom keywords, closes #955, c…
Browse files Browse the repository at this point in the history
  • Loading branch information
epoberezkin committed Feb 22, 2019
1 parent f6d25de commit 187e021
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 6 deletions.
10 changes: 4 additions & 6 deletions lib/keyword.js
Expand Up @@ -43,8 +43,6 @@ var definitionSchema = {
}
};

var validateDefinition;

/**
* Define custom keyword
* @this Ajv
Expand All @@ -56,18 +54,18 @@ function addKeyword(keyword, definition) {
/* jshint validthis: true */
/* eslint no-shadow: 0 */
var RULES = this.RULES;

if (RULES.keywords[keyword])
throw new Error('Keyword ' + keyword + ' is already defined');

if (!IDENTIFIER.test(keyword))
throw new Error('Keyword ' + keyword + ' is not a valid identifier');

if (definition) {
validateDefinition = validateDefinition || this.compile(definitionSchema);
this.validateKeyword = this.validateKeyword
|| this.compile(definitionSchema, true);

if (!validateDefinition(definition))
throw new Error('custom keyword definition is invalid: ' + this.errorsText(validateDefinition.errors));
if (!this.validateKeyword(definition))
throw new Error('custom keyword definition is invalid: ' + this.errorsText(this.validateKeyword.errors));

var dataType = definition.type;
if (Array.isArray(dataType)) {
Expand Down
48 changes: 48 additions & 0 deletions spec/issues/955_removeAdditional_custom_keywords.spec.js
@@ -0,0 +1,48 @@
'use strict';

var Ajv = require('../ajv');
require('../chai').should();


describe('issue #955: option removeAdditional breaks custom keywords', function() {
it('should support custom keywords with option removeAdditional', function() {
var ajv = new Ajv({removeAdditional: 'all'});

ajv.addKeyword('minTrimmedLength', {
type: 'string',
compile: function(schema) {
return function(str) {
return str.trim().length >= schema;
};
},
metaSchema: {type: 'integer'}
});

var schema = {
type: 'object',
properties: {
foo: {
type: 'string',
minTrimmedLength: 3
}
},
required: ['foo']
};

var validate = ajv.compile(schema);

var data = {
foo: ' bar ',
baz: ''
};
validate(data) .should.equal(true);
data .should.not.have.property('baz');

data = {
foo: ' ba ',
baz: ''
};
validate(data) .should.equal(false);
data .should.not.have.property('baz');
});
});

0 comments on commit 187e021

Please sign in to comment.