Skip to content

Commit

Permalink
docs: keywords if/then/else, #3
Browse files Browse the repository at this point in the history
  • Loading branch information
epoberezkin committed Dec 22, 2016
1 parent a4edf60 commit 3dd8aee
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Custom JSON-Schema keywords for [ajv](https://github.com/epoberezkin/ajv) valida
- [instanceof](#instanceof)
- [range and exclusiveRange](#range-and-exclusiverange)
- [propertyNames](#propertynames)
- [if/then/else](#if-then-else)
- [regexp](#regexp)
- [dynamicDefaults](#dynamicdefaults)
- [License](#license)
Expand Down Expand Up @@ -156,6 +157,34 @@ ajv.validate(schema, validData); // true
ajv.validate(schema, invalidData); // false
```

__ Please note__: This keyword will be added to the next version of the JSON-Schema standard (draft-6), after it is published the keyword will be included in Ajv as standard validation keyword.


### `if`/`then`/`else`

These keywords allow to implement conditional validation. Their values should be valid JSON-schemas. At the moment it requires using Ajv with v5 option.

If the data is valid according to the sub-schema in `if` keyword, then the result is equal to the result of data validation against the sub-schema in `then` keyword, otherwise - in `else` keyword (if `else` is absent, the validation succeeds).

```javascript
var schema = {
type: 'array',
items: {
type: 'integer',
minimum: 1,
if: { maximum: 10 },
then: { multipleOf: 2 },
else: { multipleOf: 5 }
}
};

var validItems = [ 2, 4, 6, 8, 10, 15, 20, 25 ]; // etc.

var invalidItems = [ 1, 3, 5, 11, 12 ]; // etc.
```

This keyword is [proposed](https://github.com/json-schema-org/json-schema-spec/issues/180) for the future version of JSON-Schema standard.


### `regexp`

Expand Down
2 changes: 1 addition & 1 deletion keywords/if.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ module.exports = function defFunc(ajv) {
defFunc.definition = {
macro: function (schema, parentSchema) {
if (parentSchema.then === undefined)
throw new Error('keyword then is absent');
throw new Error('keyword "then" is absent');
var cases = [ { 'if': schema, 'then': parentSchema.then } ];
if (parentSchema.else !== undefined)
cases[1] = { 'then': parentSchema.else };
Expand Down

0 comments on commit 3dd8aee

Please sign in to comment.