Skip to content

Commit

Permalink
useDefaults readme
Browse files Browse the repository at this point in the history
  • Loading branch information
epoberezkin committed Jan 9, 2016
1 parent d7dd660 commit 94a8f9a
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 10 deletions.
63 changes: 60 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ NB: [Changes in version 3.0.0](https://github.com/epoberezkin/ajv/releases/tag/3
- [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages
- i18n error messages support with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package (version >= 1.0.0)
- [filtering data](#filtering-data) from additional properties
- NEW: [assigning defaults](#assigning-defaults) to missing properties and items
- [custom keywords](#defining-custom-keywords)
- keywords `switch`, `constant`, `contains`, `patternGroups`, `formatMaximum` / `formatMinimum` and `exclusiveFormatMaximum` / `exclusiveFormatMinimum` from [JSON-schema v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [option v5](#options)
- [v5 meta-schema](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#) for schemas using v5 keywords.
- NEW: [v5 $data reference](#data-reference) to use values from the validated data as values for the schema keywords.
- [v5 meta-schema](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#) for schemas using v5 keywords
- NEW: [v5 $data reference](#data-reference) to use values from the validated data as values for the schema keywords

Currently ajv is the only validator that passes all the tests from [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (according to [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark), apart from the test that requires that `1.0` is not an integer that is impossible to satisfy in JavaScript).

Expand Down Expand Up @@ -89,6 +90,8 @@ if (!valid) console.log(ajv.errorsText());
// ...
```

See [API](#api) and [Options](#options) for more details.

ajv compiles schemas to functions and caches them in all cases (using stringified schema as a key - using [json-stable-stringify](https://github.com/substack/json-stable-stringify)), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again.

The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call).
Expand Down Expand Up @@ -425,6 +428,58 @@ This option modifies original object.
TODO: example


## Assigning defaults

With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items.

Example 1 (`default` in `properties`):

```
var ajv = Ajv({ useDefaults: true });
var schema = {
"type": "object",
"properties": {
"foo": { "type": "number" },
"bar": { "type": "string", "default": "baz" }
},
"required": [ "foo", "bar" ]
};
var data = { "foo": 1 };
var validate = ajv.compile(schema);
console.log(validate(data)); // true
console.log(data); // { "foo": 1, "bar": "baz" }
```

Example 2 (`default` in `items`):

```
var schema = {
"type": "array",
"items": [
{ "type": "number" },
{ "type": "string", "default": "foo" }
]
}
var data = [ 1 ];
var validate = ajv.compile(schema);
console.log(validate(data)); // true
console.log(data); // [ 1, "foo" ]
```

`default` keywords in other cases are ignored:

- not in `properties` or `items` subschemas
- in schemas inside `anyOf`, `oneOf` and `not` (see #42)
- in `if` subschema of v5 `switch` keyword
- in schemas generated by custom macro keywords


## API

##### Ajv(Object options) -> Object
Expand Down Expand Up @@ -568,6 +623,7 @@ Defaults:
{
allErrors: false,
removeAdditional: false,
useDefaults: false,
verbose: false,
format: 'fast',
formats: {},
Expand All @@ -578,7 +634,7 @@ Defaults:
loopRequired: Infinity,
multipleOfPrecision: false,
missingRefs: true,
loadSchema: function(uri, cb) { /* ... */ cb(err, schema); },
loadSchema: undefined, // function(uri, cb) { /* ... */ cb(err, schema); },
uniqueItems: true,
unicode: true,
beautify: false,
Expand All @@ -592,6 +648,7 @@ Defaults:

- _allErrors_: check all rules collecting all errors. Default is to return after the first error.
- _removeAdditional_: remove additional properties. Default is not to remove. If the option is 'all', then all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). If the option is `true` (or truthy), only additional properties with `additionalProperties` keyword equal to `false` are removed. If the option is 'failing', then additional properties that fail schema validation will be removed too (where `additionalProperties` keyword is schema).
- _useDefaults_: replace missing properties and items with the values from corresponding `defaults` keywords. Default behaviour is to ignore `default` keywords.
- _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default).
- _format_: formats validation mode ('fast' by default). Pass 'full' for more correct and slow validation or `false` not to validate formats at all. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode.
- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method.
Expand Down
14 changes: 7 additions & 7 deletions spec/options.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -378,24 +378,24 @@ describe('Ajv Options', function () {
items: [
{ type: 'string', default: 'abc' },
{ type: 'number', default: 1 },
{ type: 'boolean' }
]
{ type: 'boolean', default: false }
],
};

var validate = ajv.compile(schema);

var data = [];
validate(data) .should.equal(true);
data. should.eql([ 'abc', 1 ]);
data. should.eql([ 'abc', 1, false ]);

var data = [,,true];
var data = [ 'foo' ];
validate(data) .should.equal(true);
data. should.eql([ 'abc', 1, true ]);
data. should.eql([ 'foo', 1, false ]);

var data = ['foo',,'false'];
var data = ['foo', 2,'false'];
validate(data) .should.equal(false);
validate.errors .should.have.length(1);
data. should.eql([ 'foo', 1, 'false' ]);
data. should.eql([ 'foo', 2, 'false' ]);
}
});
});
Expand Down

0 comments on commit 94a8f9a

Please sign in to comment.