ajv-validator / ajv-keywords Goto Github PK
View Code? Open in Web Editor NEWAdditional JSON-Schema keywords for Ajv JSON validator
Home Page: https://ajv.js.org
License: MIT License
Additional JSON-Schema keywords for Ajv JSON validator
Home Page: https://ajv.js.org
License: MIT License
Hi, a variant of "propertyNames" keyword could strip property names in Object.prototype. It could be a fast version with a key in Object.prototype
check, and I'd like to use it whenever I allow additionalProperties. The reason I'm suggesting this is that currently quite often people just use JSON.parse
and don't consider that if they get a malicious object such as {"toString":null}
it will quite easily break downstream as some logging, string concatenation or similar will call toString
on it. Similar with other properties in Object.prototype
, and it would be nice to avoid the function call in "propertyNames" with this keyword variant.
Here is a file that depends on the ajv
and ajv-keywords
packages.
I don't know if this is a keywords-related feature or not.
I expect this to output { transition: 'FOO, transitionDuration: 30 }
Am I at fault?
What should I change?
In short I'm looking for a simple and readable way for users to add properties.
Any help is appreciated.
const Ajv = require('ajv')
const schema = {
properties: {
transition: {
type: 'string',
enum: ['FOO', 'BAR']
}
},
allOf: [
{
if: {
properties: {
transition: {
const: 'FOO'
}
}
},
then: {
properties: {
transitionDuration: {
type: 'number'
}
}
}
}
]
}
const ajv = Ajv({ removeAdditional: 'all' })
require('ajv-keywords')(ajv, 'if')
const validate = ajv.compile(schema)
const data = { transition: 'FOO', transitionDuration: 30 }
validate(data)
console.log(data)
Just jotting down notes for after #64 is merged
Allow options, similar to dynamicDefaults
toEnumCase
have option to ignore certain char when determining uniqueness ie strip out ,
and -
replace string or regex
strip html tags w/ options (alias of replace w/ defaults)
review idea of having addons for more complex/custom transforms
leftPad/rightPad/regexPad/patternCoerce string. ie 1:45
-> 01:45:00.000
floor/ceil number
Options: (WIP)
{
"type":"object",
"transforms":{
"$defaults":{
},
"name":{
"toEnumCase":{"ignorePattern":"[\.]", "ignore":[",","-"]}
},
"time":{
}
}
}
Ref: #64
Branch | Build failing 🚨 |
---|---|
Dependency | js-beautify |
Current Version | 1.6.14 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
As js-beautify is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.
I recommend you give this issue a high priority. I’m sure you can resolve this 💪
The new version differs by 22 commits.
0ac845e
1.7.0
5b3c36c
Python 1.7.0
9276881
Bump version numbers in README.md
1bd274d
Update Changelog for 1.7.0
ea252d1
Package lock update
9d733b5
Merge pull request #1243 from bitwiseman/feature/poly
cbbb2e0
Merge branch 'master' into feature/poly
453bdc9
Fixed yield function spacing
468815e
Merge pull request #1241 from simondel/master
a46f97c
README, LICENSE, CHANGELOG and package.json are always added
f56a513
Remove Object.value polyfill
641d3bc
Don't publish unnessessary files.
ed61dc1
Merge pull request #1240 from aecepoglu/unindent-chains-2
258a361
adding the generated files
2683c35
updated the js src file
There are 22 commits in total.
See the full diff
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot 🌴
Hi,
we are using schemas for strict validation and it is too easy to not add properties into required
array resulting in bugs. I want to suggest a keyword suggestion which will make this usecase much easier.
Keyword Suggestion: requireAll: true
for objects, which will force all listed properties to be required in the object
Optionally it would be nice to have a global switch for requireAll
which will force it on every validated object unless it has requireAll: false
in its definition.
if I install v. 6 myself I receive the error message that I must install the v. 5 and its not leting me install the version 5 without prompting me of the first probleme
[email protected] requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself.
[email protected] requires a peer of ajv@^5.0.0 but none is installed. You must install peer dependencies yourself.
Can you tell me how to fix this ? the "nmp ls -g" output as in the enclosed file a.txt.
a.txt
Thanks.
Hello,
I have a JSON object:
{
"body": {
"independent_prop": "123",
"a": "HELLO",
"b": "sd",
"k": 1, // should be removed after validation
"any_key": "bla" // should be removed after validation
},
}
which should be validated with the folowing situations:
independent_prop
key - should be requireda
key is "HELLO" then b is requireda
key is "WORLD" then c is requiredconst Ajv = require('ajv');
const ajv = new Ajv({
allErrors: true,
removeAdditional: true,
coerceTypes: true,
});
const fn = ajv.compile({
type: 'object',
properties: {
body: {
type: 'object',
properties: {
independent_prop: { type: 'integer' },
},
anyOf: [
{
properties: {
a: { type: 'string', const: 'HELLO' },
b: { type: 'string' },
},
// additionalProperties: false, -> { body: { a: 'HELLO', b: 'sd' } }
required: ['b'],
},
{
properties: {
a: { type: 'string', const: 'WORLD' },
c: { type: 'string' },
},
// additionalProperties: false, -> { body: { a: 'HELLO', c: 'sd' } }
required: ['c'],
}
],
// additionalProperties: false, THROWS validation errors
required: ['a', 'independent_prop'],
},
},
required: ['body'],
});
const values = {
body: {
independent_prop: '123',
a: 'HELLO',
b: 'sd',
k: 1
},
};
console.log('fn(values)', fn(values));
console.log('values', values); // `{ body: { a: 'HELLO', b: 'sd' } }`
console.log('fn.errors', fn.errors);
Is it possible to remove all keys except defined in validation schema?
Thanks,
latest release on npm is 1.5.1 but tag is missing in the repo
I am using [email protected] and [email protected]
The following code:
import ajv from "ajv"
import keywords from "ajv-keywords"
keywords(ajv)
produces:
ajv.addKeyword('instanceof', defFunc.definition);
^
TypeError: ajv.addKeyword is not a function
at defFunc (/Users/rolftimmermans/Code/tinify/framework/node_modules/ajv-keywords/keywords/instanceof.js:46:7)
Is ajv-keywords compatible with ajv 5? If not, that would be a shame since I currently need the switch
keyword but it has been removed from ajv.
Hi,
I want to send a message to the end user if he has used any additional fields other than allowed set of fields. I use additionalProperties to false. Following is my json schema.
{
type: "object",
additionalProperties : false,
properties: {
question: {
type: "string"
},
series: {
type: "string",
enum: ["all","first","last"]
}
}
}
I use ajv NPM in nodejs and for all the valid requests it returns following message.
{
"keyword": "additionalProperties",
"dataPath": "",
"schemaPath": "#/additionalProperties",
"params": {
"additionalProperty": "__proto__"
},
"message": "should NOT have additional properties"
}
I'm not sure whether I'm using the correct approach to solve my issue. I used ownProperties to true, but it didn't help.
I think if we have an option to omit the inherited field (proto) that would be really helpful.
see ajv-validator/ajv#486 for the context
When I use "pattern" as one of my schema verification properties and AJV finds an error based on the pattern, it'll return an error like:
{ keyword: 'pattern',
dataPath: '.title',
schemaPath: '#/properties/title/allOf/0/pattern',
params: { pattern: '^((?!abc).)*$' },
message: 'should match pattern "^((?!abc).)*$"' }
Knowing the information about the pattern that is failing is extremely useful to me, yet when i switch from "pattern" to "regexp" via AJV-Keywords, the error returned isn't quite as useful:
{ keyword: 'regexp',
dataPath: '.tracks[0].label_copy',
schemaPath: '#/properties/label_copy/allOf/0/regexp',
params: { keyword: 'regexp' },
message: 'should pass "regexp" keyword validation' }
not telling me which regexp has failed (e.g. ^((?!abc).)*$/i
), I know that I can derive this from schemaPath
, but having it in the message and/or the params would be incredibly useful.
This https://github.com/epoberezkin/ajv-keywords/blob/master/keywords/regexp.js#L14 doesn't take into account the unicode (u) flag when using a pattern as a string rather than an object
"regexp": "/^((?!\\b(?:CC|Closed?(\\u{002D}|\\u{2010}|\\u{2212}|\\u{2012}|\\u{2013}|\\u{2014}|\\u{2015})Caption(?:ed)?|14\\s?(x|:|\\u{2015})\\s?9|9\\s?(x|:|\\u{2015})\\s?14|16\\s?(x|:|\\u{2015})\\s?9|9\\s?(x|:|\\u{2015})\\s?16|4\\s?(x|:|\\u{2015})\\s?3|3\\s?(x|:|\\u{2015})\\s?4|\\d+\\s?fps|EPK|Video|Clip|Press\\s(?:Kit|Pack))\\b).)*$/u
would fail whereas
"regexp": {
"pattern": "^((?!\\b(?:CC|Closed?(\\u{002D}|\\u{2010}|\\u{2212}|\\u{2012}|\\u{2013}|\\u{2014}|\\u{2015})Caption(?:ed)?|14\\s?(x|:|\\u{2015})\\s?9|9\\s?(x|:|\\u{2015})\\s?14|16\\s?(x|:|\\u{2015})\\s?9|9\\s?(x|:|\\u{2015})\\s?16|4\\s?(x|:|\\u{2015})\\s?3|3\\s?(x|:|\\u{2015})\\s?4|\\d+\\s?fps|EPK|Video|Clip|Press\\s(?:Kit|Pack))\\b).)*$",
"flags": "u"
}
passes.
When I try the example from the README:
var Ajv = require('ajv');
var ajv = new Ajv;
require('ajv-keywords')(ajv);
ajv.validate({ instanceof: 'RegExp' }, /.*/); // true
ajv.validate({ instanceof: 'RegExp' }, '.*'); // false
I get keyword select requires $data option
.
It still seems to work, but I don't know what to make of the warning.
npm WARN [email protected] requires a peer 0f [email protected] but none is installed. You must install peer dependencies yourself.
For screenshot please refer- Firebase functions deploy npm error
Error: invalid "instanceof" keyword value Promise
at getConstructor (node_modules/webpack/node_modules/ajv-keywords/keywords/instanceof.js:52:11)
at Ajv.compile (node_modules/webpack/node_modules/ajv-keywords/keywords/instanceof.js:21:27)
at Object.useCustomRule (node_modules/webpack/node_modules/ajv/lib/compile/index.js:275:26)
at Object.generate_custom [as code] (node_modules/webpack/node_modules/ajv/lib/dotjs/custom.js:32:24)
at Object.generate_validate [as validate] (node_modules/webpack/node_modules/ajv/lib/dotjs/validate.js:347:35)
Per the doc:
This keyword allows a string to be modified before validation.
But when I ran the code below:
const Ajv = require('ajv');
const ajv = new Ajv();
require('ajv-keywords')(ajv, ['transform']);
const schema = {
type: 'array',
items: {
type:'string',
transform: ['trim'],
format: 'email'
}
};
const data = [' [email protected] '];
console.log(ajv.validate(schema, data));
console.log(data);
I got:
false
[ ' [email protected] ' ]
The keyword format
performed before the transform
.
Hi, how to use switch in sub schema ? It's only working if switch is in the root schema.
exemple:
Maybe there is a way to use properties selector in the switch keyword that is at root position ?
like "object1.object2.something" ?
Thanks
a typical default is like like bar/baz
below
"type": "object",
"properties": {
"foo": { "type": "number" },
"bar": { "type": "string", "default": "baz" }
},
"required": [ "foo", "bar" ]
};
dynamicDefaults
should be
"type": "object",
"properties": {
"foo": { "type": "number" },
"bar": { "type": "string", "dynamicDefaults": "timestamp" }
},
"required": [ "foo", "bar" ]
};
and it should also work with required
your docs says it does not
The properties used in dynamicDefaults should not be added to required keyword (or validation will fail), because unlike default this keyword is processed after validation.
npm WARN [email protected] requires a peer of ajv@>=4.10.0 but none was installed.
I'm referencing a schema, bar.json, that sits in the same directory as my schema as follows:
"selectCases":{
"foo": {
"properties": {
"id": {},
"bar": {
"$ref": "bar.json"
}
}
}
}
I'm receiving the error:
can't resolve reference bar.json from id #
I thought that this absolute URI reference would work?
schema
in an array and in v3.3.0 it assumes it's a string causing:
TypeError: Cannot read property 'hash' of undefined
at Object.toEnumCase (transform.js:21)
at g.eval (transform.js:57)
at validate (eval at w (ajv.min.js:NaN), <anonymous>:3:15305)
v3.2.0 = https://github.com/epoberezkin/ajv-keywords/blob/v3.2.0/keywords/transform.js#L14
v3.3.0 = https://github.com/epoberezkin/ajv-keywords/blob/v3.3.0/keywords/transform.js#L33
Do you have a meta schema that includes your custom keywords by any chance?
I would like to validate schemas themselves and intend to allow your custom keyword extensions when creating schemas.
Essentially I am looking for the equivalent to this meta schema: http://json-schema.org/draft-07/schema
Thanks for the excellent library!
While working on webpack/webpack-cli#240 the need for validating a Promise
came up. It looks like the only way to use instanceof
to validate this constructor type is by augmenting the CONSTRUCTORS
manually (similar to adding a custom constructor).
It seems like the Promise
constructor could be supported in a similar manner as Buffer
.
I've opened a PR proposing this update #51 – looking forward to the discussion, thanks!
is there a CDN browser version that you currently maintain?
Thanks
Minimal test case:
const Ajv = require('ajv');
const ajvKeywords = require('ajv-keywords');
const ajv = new Ajv({allErrors: true, $data: true});
ajvKeywords(ajv);
const validate = ajv.compile({
type: 'object',
required: ['action'],
properties: {
action: {type: 'string'}
},
select: {$data: '0/action'},
selectCases: {
start: {},
finish: {}
},
selectDefault: false
});
validate({action: 'bad'});
console.log(validate.errors);
The script produces the following error:
[{
keyword: 'select',
dataPath: '',
schemaPath: '#/select',
params: { keyword: 'select' },
message: 'should pass "select" keyword validation'
}]
I'd like to request that params
for this case be expanded to include allowedValues: [ 'start', 'finish' ]
.
Branch | Build failing 🚨 |
---|---|
Dependency | eslint |
Current Version | 4.13.1 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
eslint is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
complexity
rule (fixes #8535) (#9754) (Kevin Partington)valid-typeof
example (#9753) (Teddy Katz)source
property a little more subtle (#9735) (Jed Fox)lines-between-class-members
(fixes #9665) (#9680) (sakabar)The new version differs by 19 commits.
8d166b4
4.14.0
5a29612
Build: changelog update for 4.14.0
be2f57e
Update: support separate requires in one-var. (fixes #6175) (#9441)
370d614
Docs: Fix typos (#9751)
8196c45
Chore: Reorganize CLI options and associated docs (#9758)
75c7419
Update: Logical-and is counted in complexity
rule (fixes #8535) (#9754)
eb4b1e0
Docs: reintroduce misspelling in valid-typeof
example (#9753)
ae51eb2
New: Add allowImplicit option to array-callback-return (fixes #8539) (#9344)
e9d5dfd
Docs: improve no-extra-parens formatting (#9747)
37d066c
Chore: Add unit tests for overrides glob matching. (#9744)
805a94e
Chore: Fix typo in CLIEngine test name (#9741)
1c2aafd
Update: Improve parser integrations (fixes #8392) (#8755)
4ddc131
Upgrade: debug@^3.1.0 (#9731)
f252c19
Docs: Make the lint message source
property a little more subtle (#9735)
5a5c23c
Docs: fix the link to contributing page (#9727)
There are 19 commits in total.
See the full diff
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
Would be great if this plugin provided built-in typings
like ajv
does. Here is the declaration I'm using in my own projects:
// ajv-keywords.d.ts
declare module 'ajv-keywords' {
import { Ajv } from 'ajv';
type AdditionalKeywords =
| 'typeof'
| 'instanceof'
| 'range'
| 'exclusiveRange'
| 'switch'
| 'select'
| 'selectCases'
| 'selectDefault'
| 'patternRequired'
| 'prohibited'
| 'deepProperties'
| 'deepRequired'
| 'uniqueItemProperties'
| 'regexp'
| 'formatMaximum'
| 'formatMinimum'
| 'formatExclusiveMaximum'
| 'formatExclusiveMinimum'
| 'dynamicDefaults';
function keywords(ajv: Ajv, include?: AdditionalKeywords | AdditionalKeywords[]): void;
export = keywords;
}
BONUS: it would be really great if this package also provided a module augmentation for json-schema
. That way by importing this module, the additional keywords are made available on the interfaces exported by json-schema
. Below is an (incomplete) example of what that would look like:
// json-schema.d.ts
import * as JsonSchema from 'json-schema';
declare module 'json-schema' {
type BuiltinDynamics =
| 'timestamp'
| 'datetime'
| 'date'
| 'time'
| 'random'
| 'randomint'
| 'seq';
type DynamicDefault = BuiltinDynamics | string;
type DynamicDefaultWithArgs = { func: DynamicDefault, [key: string]: any };
interface KeywordAugmentations {
dynamicDefaults?: {
[key: string]: DynamicDefault | DynamicDefaultWithArgs;
}
// define other keywords...
}
export interface JSONSchema6 extends KeywordAugmentations { }
export interface JSONSchema4 extends KeywordAugmentations { }
}
This is a similar schema as in json-schema-org/json-schema-spec#180 (comment):
var Ajv = require('ajv');
var schema = {
"properties": {
"foo": {
"type": "integer"
},
"bar": {
"type": "integer",
"default": 1
},
"pets": {
"type": "array",
"items": {
"oneOf": [
{
"if": { "properties": { "type": { "const": "cat" } } },
"then": { "$ref": "#/definitions/cat_pet" },
"else": false
},
{
"if": { "properties": { "type": { "const": "snake" } } },
"then": { "$ref": "#/definitions/snake_pet" },
"else": false
}
]
}
}
},
"definitions": {
"cat_pet": {
"type": "object",
"properties": {
"type": { "type": "string", "const": "cat" },
"fur_color": { "type": "string", "enum": ["black", "white", "orange"], "default": "black" }
},
"required": ["type", "fur_color"]
},
"snake_pet": {
"type": "object",
"properties": {
"type": { "type": "string", "const": "snake" },
"overall_length": { "type": "integer", "minimum": 1, "default": 1 }
},
"required": ["type", "overall_length"]
}
}
};
data = {
"foo": 123,
"pets": [
{
"type": "cat",
"fur_color": "white",
"inv": "alid"
},
{
"type": "snake",
"inv": "alid"
}
]
};
var ajv = new Ajv({removeAdditional: true, useDefaults: true});
require('ajv-keywords')(ajv, 'if');
var validate = ajv.compile(schema);
var valid = validate(data);
console.log(data);
if (!valid) console.log(validate.errors);
This time I try to have Ajv coerce the data into a valid structure, but I get errors:
[ { keyword: 'switch', dataPath: '.pets[1]', schemaPath: '#/properties/pets/items/oneOf/0/switch', params: { caseIndex: 1 }, message: 'should pass "switch" keyword validation' }, { keyword: 'if', dataPath: '.pets[1]', schemaPath: '#/properties/pets/items/oneOf/0/if', params: { keyword: 'if' }, message: 'should pass "if" keyword validation' }, { keyword: 'required', dataPath: '.pets[1]', schemaPath: '#/definitions/snake_pet/required', params: { missingProperty: 'overall_length' }, message: 'should have required property \'overall_length\'' }, { keyword: 'if', dataPath: '.pets[1]', schemaPath: '#/properties/pets/items/oneOf/1/if', params: { keyword: 'if' }, message: 'should pass "if" keyword validation' }, { keyword: 'oneOf', dataPath: '.pets[1]', schemaPath: '#/properties/pets/items/oneOf', params: {}, message: 'should match exactly one schema in oneOf' } ]
The below code throws the error: TypeError: equal is not a function
.
const ajv = require('ajv')();
require('ajv-keywords')(ajv);
ajv.validate({
properties: {
array: {
type: 'array',
uniqueItemProperties: ['id']
}
}
}, {
array: [{
id: 0
}, {
id: 0
}]
})
Version info
ajv 6.1.1
ajv-keywords 3.1.0
node 9.5.0
Ajv options
None.
JSON Schema
{
"properties": {
"start": {
"type": "string",
"format": "date"
},
"end": {
"type": "string",
"format": "date",
"formatMinimum": {
"$data": "1/start"
}
}
}
}
Sample data
{"start": "2013-02-27", "end": "2013-02-21"}
Code
const Ajv = require('ajv');
const ajv = new Ajv();
require('ajv-keywords')(ajv, 'formatMinimum');
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) console.log(validate.errors);
The RunKit document currently doesn't work because of a RunKit issue (they seem to be missing the "fast-json-stable-stringify" module), but here's the link anyway in case it gets fixed: https://runkit.com/soullesswaffle/5a784e73af44fe0012deed01
Error message
str.replace is not a function
at escapeQuotes ./node_modules/ajv/lib/compile/util.js:116
at Object.toQuotedString ./node_modules/ajv/lib/compile/util.js:187
at Ajv.generate__formatLimit ./node_modules/ajv-keywords/keywords/dotjs/_formatLimit.js:179
at Object.useCustomRule ./node_modules/ajv/lib/compile/index.js:277
at Object.generate_custom [as code] ./node_modules/ajv/lib/dotjs/custom.js:32
at Object.generate_validate [as validate] ./node_modules/ajv/lib/dotjs/validate.js:334
at Object.generate_properties [as code] ./node_modules/ajv/lib/dotjs/properties.js:194
at generate_validate ./node_modules/ajv/lib/dotjs/validate.js:334
at localCompile ./node_modules/ajv/lib/compile/index.js:86
at Ajv.compile ./node_modules/ajv/lib/compile/index.js:55
at Ajv._compile ./node_modules/ajv/lib/ajv.js:353
at Ajv.compile ./node_modules/ajv/lib/ajv.js:113
at Object.<anonymous> index.js:6:0
at Module._compile module.js:660
Expected results
The schema compiles, and upon validation it says that the data is invalid because end
< start
.
Additional info
It's possible that this worked at some point, at least according to this Stack Overflow answer.
According to the ajv docs, $data
reference is supported for the formatMinimum keyword.
However, according to the ajv-keywords docs, the value of the keyword should be a string, and the implementation seems to expect this as well.
Hello,
From the readme for deepProperties:
This keyword allows to validate deep properties (identified by JSON pointers).
I have a need to validate 'cousin' properties inside an array. I've tried this:
let schema = {
deepProperties : { "/parent/child1/grandchild1" : {
deepProperties : { "2/child2/grandchild2" : { const : true }}
}}
};
let data = {
parent : {
child1 : {
grandchild1: true
},
child2 : {
grandchild2: false
}
}
};
And got: keyword schema is invalid: data should match format "json-pointer", data property name '2/child2/grandchild2' is invalid.
Tracing a bit - it looks like the validation code from ajv/lib doesn't support relative pointers.
I can build another custom keyword to wrap deepProperties I think, but wanted to report this either for fixing or for clarifying.
Thanks!
Koby
When you create a Date
object in UTC timezone in JavaScript as follows
new Date(10000, null)
and convert it to ISO string, you get +010000-01-01T00:00:00.000Z
(notice the leading +0
string).
This seems to follow the ISO 8601 standard.
This breaks the formatMaximum
(and possibly also formatMinimum
) validation because the dates are compared as plain strings, ie. eventually you get to a point where your compare "2018"
and "+010000"
and as far as JS strings are concerned, 2018
is greater, even though the intention was to compare year 2018 and year 10000.
Here, the ISO string is split into year component:
And here is the actual string comparison of the two dates:
npm WARN [email protected] requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself.
The readme lists the "patternsGroups" keyword as deprecated.
It seems like there are some cases where it could be useful -- so I'm curious, why was it removed?
Is it because the good majority of use-cases can also be accomplished with "patternProperties" + "additionalProperties: false", and so keeping it is kind of redundant/not worth the maintenance effort?
(P.S. Great library, by the way. I especially like the ability to add custom keywords, as it lets you integrate pretty much all (if not all) validation logic into the schema system.)
With this schema:
{
'type': 'object',
'properties': {
'contactClass': { 'type': 'string' }
},
'if': { 'properties': { 'type': { 'const': 'person' } } },
'then': {
'properties': {
'type': { 'const': 'person' },
'firstName': { 'type': 'string' }
}
},
'else': {
'if': { 'properties': { 'type': { 'const': 'corporation' } } },
'then': {
'properties': {
'type': { 'const': 'corporation' },
'compName': { 'type': 'string', 'title': 'Company Name' }
}
}
}
And this instance:
{
type: 'corporation',
compName: 12
}
The following errors are reported:
[
{
"keyword": "type",
"dataPath": "/compName",
"schemaPath": "#/switch/1/then/switch/0/then/properties/compName/type",
"params": {
"type": "string"
}
},
{
"keyword": "if",
"dataPath": "",
"schemaPath": "#/switch/1/then/if",
"params": {
"keyword": "if"
}
},
{
"keyword": "if",
"dataPath": "",
"schemaPath": "#/if",
"params": {
"keyword": "if"
}
}
]
I would expect that the schemaPath
properties on the errors would reflect the actual schema. This occurs if I just add the if
keyword and no other keywords.
import * as Ajv from 'ajv'
import * as keywords form 'ajv-keywords'
const ajv = keywords(
{
allErrors: true,
jsonPointers: true,
messages: false
},
'if'
)
Hi, I might be doing something wrong so correct me please... Thanks
So, based on my understanding the two should be the same:
date: {
format: "date",
formatMaximum: "2016-02-06",
formatExclusiveMaximum: true
}
or
date: {
allOf: [
{ format: "date" },
{ formatMaximum: "2016-02-06" },
{ formatExclusiveMaximum: true }
]
}
Expected: for those two to give same result
Actual: getting an error running second one as listed below
PS We're using custom keywords and $data like this:
const withCustomKeywords = pipe(
itemPropEqByStrToPropName,
arrayValuesEqByStrToPropNames,
ajvKeywords
);
const makeAjv = (schemas, options) =>
withCustomKeywords(
new Ajv({ $data: true, jsonPointers: true, ...options })
).addSchema(schemas);
TypeError: Cannot read property '$data' of undefined
at Ajv.generate__formatLimit (node_modules/ajv-keywords/keywords/dotjs/_formatLimit.js:19:52) at Object.useCustomRule (node_modules/ajv/lib/compile/index.js:277:25) at Object.generate_custom [as code] (node_modules/ajv/lib/dotjs/custom.js:32:24) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:334:35) at Object.generate_allOf [as code] (node_modules/ajv/lib/dotjs/allOf.js:25:27) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:334:35) at Object.generate_properties [as code] (node_modules/ajv/lib/dotjs/properties.js:194:26) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:334:35) at Object.generate_allOf [as code] (node_modules/ajv/lib/dotjs/allOf.js:25:27) at generate_validate (node_modules/ajv/lib/dotjs/validate.js:334:35) at Ajv.localCompile (node_modules/ajv/lib/compile/index.js:86:22) at Ajv.resolve (node_modules/ajv/lib/compile/resolve.js:54:19) at Object.resolveRef (node_modules/ajv/lib/compile/index.js:187:21) at Object.generate_ref [as code] (node_modules/ajv/lib/dotjs/ref.js:21:22) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:261:37) at Object.generate_properties [as code] (node_modules/ajv/lib/dotjs/properties.js:300:26) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:334:35) at Object.generate_properties [as code] (node_modules/ajv/lib/dotjs/properties.js:194:26) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:334:35) at Object.generate_allOf [as code] (node_modules/ajv/lib/dotjs/allOf.js:25:27) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:334:35) at Object.generate_properties [as code] (node_modules/ajv/lib/dotjs/properties.js:194:26) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:334:35) at Object.generate_allOf [as code] (node_modules/ajv/lib/dotjs/allOf.js:25:27) at generate_validate (node_modules/ajv/lib/dotjs/validate.js:334:35) at Ajv.localCompile (node_modules/ajv/lib/compile/index.js:86:22) at Ajv.resolve (node_modules/ajv/lib/compile/resolve.js:54:19) at Object.resolveRef (node_modules/ajv/lib/compile/index.js:187:21) at Object.generate_ref [as code] (node_modules/ajv/lib/dotjs/ref.js:21:22) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:261:37) at Object.generate_properties [as code] (node_modules/ajv/lib/dotjs/properties.js:300:26) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:334:35) at Object.generate_properties [as code] (node_modules/ajv/lib/dotjs/properties.js:194:26) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:334:35) at Object.generate_allOf [as code] (node_modules/ajv/lib/dotjs/allOf.js:25:27) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:334:35) at Object.generate_properties [as code] (node_modules/ajv/lib/dotjs/properties.js:194:26) at generate_validate (node_modules/ajv/lib/dotjs/validate.js:334:35) at Ajv.localCompile (node_modules/ajv/lib/compile/index.js:86:22) at Ajv.resolve (node_modules/ajv/lib/compile/resolve.js:54:19) at Object.resolveRef (node_modules/ajv/lib/compile/index.js:187:21) at Object.generate_ref [as code] (node_modules/ajv/lib/dotjs/ref.js:21:22) at Object.generate_validate [as validate] (node_modules/ajv/lib/dotjs/validate.js:261:37) at Object.generate_allOf [as code] (node_modules/ajv/lib/dotjs/allOf.js:25:27) at generate_validate (node_modules/ajv/lib/dotjs/validate.js:334:35) at localCompile (node_modules/ajv/lib/compile/index.js:86:22) at Ajv.compile (node_modules/ajv/lib/compile/index.js:55:13) at _getSchemaFragment (node_modules/ajv/lib/ajv.js:222:27) at Ajv.getSchema (node_modules/ajv/lib/ajv.js:211:30) at validation.js:36:66 at retrieveWithCache (validation.js:12:59) at validation.js:36:12 at loiSubmissionReadiness (submissionReadiness.js:121:34) at Object.<anonymous> (__tests__/submissionReadiness.test.js:249:60) at new Promise (<anonymous>) at Promise.resolve.then.el (../../node_modules/p-map/index.js:46:16) at <anonymous>
Possible approaches:
TypeScript input:
import * as Ajv from 'ajv';
import * as AjvKeywords from 'ajv-keywords';
const ajv = new Ajv({
$data: true,
messages: true,
verbose: true,
allErrors: true
});
AjvKeywords(ajv);
const schema = {
type: 'object',
properties: {
Fee: {
select: { $data: '1/Type' },
selectCases: {
TYPE1: { maximum: 100 },
TYPE2: { maximum: 200 }
},
type: 'number'
},
Type: {
type: 'string'
}
}
};
const validate = ajv.compile(schema);
const valid = validate({
Type: 'TYPE1',
Fee: 150
});
if (!valid) {
console.log(validate.errors);
}
Output:
[ { keyword: 'maximum',
dataPath: '',
schemaPath: '#/properties/Fee/select',
params: { comparison: '<=', limit: 100, exclusive: undefined },
message: 'should be <= 100',
schema: 'TYPE1',
parentSchema: { maximum: 100 },
data: 150 } ]
I would expect dataPath
to be .Fee
but it's empty.
"dependencies": {
"ajv": "^5.0.4-beta",
"ajv-keywords": "2.0.1-beta.2"
}
Could you please publish ajv-keywords with updated ajv requirement? Latest ajv 5.0.4-beta.0
.
Example code below throws the following error when it attempts to compile selectSchema2:
/Users/sirockin/source/f2/f2-schema/node_modules/ajv/lib/dotjs/ref.js:61
throw new it.MissingRefError(it.baseId, $schema, $message);
^
Error: can't resolve reference defs.json#/definitions/int from id #
Example code:
var Ajv = require('ajv');
var schema = {
"$id": "http://example.com/schemas/schema.json",
"type": "object",
"properties": {
"foo": { "$ref": "defs.json#/definitions/int" },
"bar": { "$ref": "defs.json#/definitions/str" }
}
};
var selectSchema1={
"$id": "http://example.com/schemas/select1.json",
type: "object",
required: ['kind'],
properties: {
kind: { type: 'string' }
},
select: { $data: '0/kind' },
selectCases: {
foo: {
required: ['foo'],
properties: {
kind: {},
foo: { type: 'string' }
},
additionalProperties: false
},
bar: {
required: ['bar'],
properties: {
kind: {},
bar: { type: 'number' }
},
additionalProperties: false
}
},
selectDefault: {
propertyNames: {
not: { enum: ['foo', 'bar'] }
}
}
};
var selectSchema2={
"$id": "http://example.com/schemas/select2.json",
type: "object",
required: ['kind'],
properties: {
kind: { type: 'string' }
},
select: { $data: '0/kind' },
selectCases: {
foo: {
required: ['foo'],
properties: {
kind: {},
foo: { "$ref": "defs.json#/definitions/int" }
},
additionalProperties: false
},
bar: {
required: ['bar'],
properties: {
kind: {},
bar: { type: 'number' }
},
additionalProperties: false
}
},
selectDefault: {
propertyNames: {
not: { enum: ['foo', 'bar'] }
}
}
};
var defsSchema = {
"$id": "http://example.com/schemas/defs.json",
"definitions": {
"int": { "type": "integer" },
"str": { "type": "string" }
}
};
// Validate against simple schema
var ajv = new Ajv({schemas: [schema, defsSchema]});
var validate = ajv.getSchema('http://example.com/schemas/schema.json');
var result = validate({ foo:2});
console.log("Simple schema validation result: " + result);
// Validate against select schema
ajv = new Ajv({schemas: [selectSchema1, defsSchema],$data:true});
require('ajv-keywords')(ajv, 'select');
validate = ajv.getSchema('http://example.com/schemas/select1.json');
var result = validate({ kind: 'foo', foo:"blah" });
console.log("Select schema validation result: " + result);
// Validate against select schema with refs - throws an error
ajv = new Ajv({schemas: [selectSchema2, defsSchema],$data:true});
require('ajv-keywords')(ajv,'select');
validate = ajv.getSchema('http://example.com/schemas/select2.json'); // Error thrown here
var result = validate({ kind: 'foo', foo: 'any' });
console.log("Select with refs schema validation result: " + result);
can I check for previously generated validation errors, while validating the custom keyword?
this is the best I could come up with so far:
ajv.addKeyword('fromInput',{
modifying:true,
compile: function (schema, parentSchema, it){
return function () {
// console.log(it)
return true;
}
},
errors: true
});
please note that I used the option to define "compile:" fn only because this option allows the "it" context, so from there I can access "it" or "it.self".
To be clear, and also to confirm that I interpretting this feature correctly (?), I placed the custom keyword as very last in the schema, so I assume that at validation time all previous keywords will be validated and errors generated. So during validation of this custom keyword I need to access those validation errors and make some decisions based on that.
However, I don't know where to go from here (see above code), because in the debugger I don't see any errors. it.self does have "errors" property, but it's =null.
thanks
To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:
.travis.yml
If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.
Greenkeeper has checked the engines
key in any package.json
file, the .nvmrc
file, and the .travis.yml
file, if present.
engines
was only updated if it defined a single version, not a range..nvmrc
was updated to Node.js 10.travis.yml
was only changed if there was a root-level node_js
that didn’t already include Node.js 10, such as node
or lts/*
. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.For many simpler .travis.yml
configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
see comments in #80
#80 (comment)
#80 (comment)
Branch | Build failing 🚨 |
---|---|
Dependency | mocha |
Current Version | 4.0.1 |
Type | devDependency |
This version is covered by your current version range and after updating it in your project the build failed.
mocha is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
This is mainly a "housekeeping" release.
Welcome @Bamieh and @xxczaki to the team!
progress
reporter now accepts reporter options (@canoztokmak)xit
in bdd
interface now properly returns its Test
object (@Bamieh)--help
will now help you even if you have a mocha.opts
(@Zarel)--no-diff
flag will completely disable diff output (@CapacitorSet)docs/
(@boneskull)The new version differs by 409 commits.
6b9ddc6
Release v4.1.0
3c4b116
update CHANGELOG for v4.1.0
5be22b2
options.reporterOptions
are used for progress reporter
ea96b18
add .fossaignore [ci skip]
adc67fd
Revert "[ImgBot] optimizes images (#3175)"
ae3712c
[ImgBot] optimizes images (#3175)
33db6b1
Use x64 node on appveyor
4a6e095
Run appveyor tests on x64 platform. Might enable sharp installation
3abed9b
Lint netlify-headers script
119543e
Add preconnect for doubleclick domain that google analytics results in contacting
bd5109e
Remove crossorigin='anonymous' from preconnect hints. Only needed for fonts, xhr and es module loads
123ee4f
Handle the case where all avatars are already loaded at the time when the script exexecutes
64deadc
Specific value for inlining htmlimages to guarantee logo is inlined
8f1ded4
https urls where possible
d5a5125
Be explicit about styling of screenshot images
There are 250 commits in total.
See the full diff
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.