source: trip-planner-front/node_modules/ajv-keywords/README.md@ b738035

Last change on this file since b738035 was e29cc2e, checked in by Ema <ema_spirova@…>, 3 years ago

primeNG components

  • Property mode set to 100644
File size: 25.6 KB
RevLine 
[6a3a178]1# ajv-keywords
2
3Custom JSON-Schema keywords for [Ajv](https://github.com/epoberezkin/ajv) validator
4
5[![Build Status](https://travis-ci.org/ajv-validator/ajv-keywords.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv-keywords)
6[![npm](https://img.shields.io/npm/v/ajv-keywords.svg)](https://www.npmjs.com/package/ajv-keywords)
7[![npm downloads](https://img.shields.io/npm/dm/ajv-keywords.svg)](https://www.npmjs.com/package/ajv-keywords)
8[![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv-keywords/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv-keywords?branch=master)
9[![Dependabot](https://api.dependabot.com/badges/status?host=github&repo=ajv-validator/ajv-keywords)](https://app.dependabot.com/accounts/ajv-validator/repos/60477053)
10[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
11
12
13## Contents
14
15- [Install](#install)
16- [Usage](#usage)
17- [Keywords](#keywords)
18 - [Types](#types)
19 - [typeof](#typeof)
20 - [instanceof](#instanceof)
21 - [Keywords for numbers](#keywords-for-numbers)
22 - [range and exclusiveRange](#range-and-exclusiverange)
23 - [Keywords for strings](#keywords-for-strings)
24 - [regexp](#regexp)
25 - [formatMaximum / formatMinimum and formatExclusiveMaximum / formatExclusiveMinimum](#formatmaximum--formatminimum-and-formatexclusivemaximum--formatexclusiveminimum)
26 - [transform](#transform)<sup>\*</sup>
27 - [Keywords for arrays](#keywords-for-arrays)
28 - [uniqueItemProperties](#uniqueitemproperties)
29 - [Keywords for objects](#keywords-for-objects)
30 - [allRequired](#allrequired)
31 - [anyRequired](#anyrequired)
32 - [oneRequired](#onerequired)
33 - [patternRequired](#patternrequired)
34 - [prohibited](#prohibited)
35 - [deepProperties](#deepproperties)
36 - [deepRequired](#deeprequired)
37 - [Compound keywords](#compound-keywords)
38 - [switch](#switch) (deprecated)
39 - [select/selectCases/selectDefault](#selectselectcasesselectdefault) (BETA)
40 - [Keywords for all types](#keywords-for-all-types)
41 - [dynamicDefaults](#dynamicdefaults)<sup>\*</sup>
42- [Security contact](#security-contact)
43- [Open-source software support](#open-source-software-support)
44- [License](#license)
45
46<sup>\*</sup> - keywords that modify data
47
48
49## Install
50
51```
52npm install ajv-keywords
53```
54
55
56## Usage
57
58To add all available keywords:
59
60```javascript
61var Ajv = require('ajv');
62var ajv = new Ajv;
63require('ajv-keywords')(ajv);
64
65ajv.validate({ instanceof: 'RegExp' }, /.*/); // true
66ajv.validate({ instanceof: 'RegExp' }, '.*'); // false
67```
68
69To add a single keyword:
70
71```javascript
72require('ajv-keywords')(ajv, 'instanceof');
73```
74
75To add multiple keywords:
76
77```javascript
78require('ajv-keywords')(ajv, ['typeof', 'instanceof']);
79```
80
81To add a single keyword in browser (to avoid adding unused code):
82
83```javascript
84require('ajv-keywords/keywords/instanceof')(ajv);
85```
86
87
88## Keywords
89
90### Types
91
92#### `typeof`
93
94Based on JavaScript `typeof` operation.
95
96The value of the keyword should be a string (`"undefined"`, `"string"`, `"number"`, `"object"`, `"function"`, `"boolean"` or `"symbol"`) or array of strings.
97
98To pass validation the result of `typeof` operation on the value should be equal to the string (or one of the strings in the array).
99
100```
101ajv.validate({ typeof: 'undefined' }, undefined); // true
102ajv.validate({ typeof: 'undefined' }, null); // false
103ajv.validate({ typeof: ['undefined', 'object'] }, null); // true
104```
105
106
107#### `instanceof`
108
109Based on JavaScript `instanceof` operation.
110
111The value of the keyword should be a string (`"Object"`, `"Array"`, `"Function"`, `"Number"`, `"String"`, `"Date"`, `"RegExp"`, `"Promise"` or `"Buffer"`) or array of strings.
112
113To pass validation the result of `data instanceof ...` operation on the value should be true:
114
115```
116ajv.validate({ instanceof: 'Array' }, []); // true
117ajv.validate({ instanceof: 'Array' }, {}); // false
118ajv.validate({ instanceof: ['Array', 'Function'] }, function(){}); // true
119```
120
121You can add your own constructor function to be recognised by this keyword:
122
123```javascript
124function MyClass() {}
125var instanceofDefinition = require('ajv-keywords').get('instanceof').definition;
126// or require('ajv-keywords/keywords/instanceof').definition;
127instanceofDefinition.CONSTRUCTORS.MyClass = MyClass;
128
129ajv.validate({ instanceof: 'MyClass' }, new MyClass); // true
130```
131
132
133### Keywords for numbers
134
135#### `range` and `exclusiveRange`
136
137Syntax sugar for the combination of minimum and maximum keywords, also fails schema compilation if there are no numbers in the range.
138
139The value of this keyword must be the array consisting of two numbers, the second must be greater or equal than the first one.
140
141If the validated value is not a number the validation passes, otherwise to pass validation the value should be greater (or equal) than the first number and smaller (or equal) than the second number in the array. If `exclusiveRange` keyword is present in the same schema and its value is true, the validated value must not be equal to the range boundaries.
142
143```javascript
144var schema = { range: [1, 3] };
145ajv.validate(schema, 1); // true
146ajv.validate(schema, 2); // true
147ajv.validate(schema, 3); // true
148ajv.validate(schema, 0.99); // false
149ajv.validate(schema, 3.01); // false
150
151var schema = { range: [1, 3], exclusiveRange: true };
152ajv.validate(schema, 1.01); // true
153ajv.validate(schema, 2); // true
154ajv.validate(schema, 2.99); // true
155ajv.validate(schema, 1); // false
156ajv.validate(schema, 3); // false
157```
158
159
160### Keywords for strings
161
162#### `regexp`
163
164This keyword allows to use regular expressions with flags in schemas (the standard `pattern` keyword does not support flags).
165
166This keyword applies only to strings. If the data is not a string, the validation succeeds.
167
168The value of this keyword can be either a string (the result of `regexp.toString()`) or an object with the properties `pattern` and `flags` (the same strings that should be passed to RegExp constructor).
169
170```javascript
171var schema = {
172 type: 'object',
173 properties: {
174 foo: { regexp: '/foo/i' },
175 bar: { regexp: { pattern: 'bar', flags: 'i' } }
176 }
177};
178
179var validData = {
180 foo: 'Food',
181 bar: 'Barmen'
182};
183
184var invalidData = {
185 foo: 'fog',
186 bar: 'bad'
187};
188```
189
190
191#### `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum`
192
193These keywords allow to define minimum/maximum constraints when the format keyword defines ordering.
194
195These keywords apply only to strings. If the data is not a string, the validation succeeds.
196
197The value of keyword `formatMaximum` (`formatMinimum`) should be a string. This value is the maximum (minimum) allowed value for the data to be valid as determined by `format` keyword. If `format` is not present schema compilation will throw exception.
198
199When this keyword is added, it defines comparison rules for formats `"date"`, `"time"` and `"date-time"`. Custom formats also can have comparison rules. See [addFormat](https://github.com/epoberezkin/ajv#api-addformat) method.
200
201The value of keyword `formatExclusiveMaximum` (`formatExclusiveMinimum`) should be a boolean value. These keyword cannot be used without `formatMaximum` (`formatMinimum`). If this keyword value is equal to `true`, the data to be valid should not be equal to the value in `formatMaximum` (`formatMinimum`) keyword.
202
203```javascript
204require('ajv-keywords')(ajv, ['formatMinimum', 'formatMaximum']);
205
206var schema = {
207 format: 'date',
208 formatMinimum: '2016-02-06',
209 formatMaximum: '2016-12-27',
210 formatExclusiveMaximum: true
211}
212
213var validDataList = ['2016-02-06', '2016-12-26', 1];
214
215var invalidDataList = ['2016-02-05', '2016-12-27', 'abc'];
216```
217
218
219#### `transform`
220
221This keyword allows a string to be modified before validation.
222
223These keywords apply only to strings. If the data is not a string, the transform is skipped.
224
225There are limitation due to how ajv is written:
226- a stand alone string cannot be transformed. ie `data = 'a'; ajv.validate(schema, data);`
227- currently cannot work with `ajv-pack`
228
229**Supported options:**
230- `trim`: remove whitespace from start and end
231- `trimLeft`: remove whitespace from start
232- `trimRight`: remove whitespace from end
233- `toLowerCase`: case string to all lower case
234- `toUpperCase`: case string to all upper case
235- `toEnumCase`: case string to match case in schema
236
237Options are applied in the order they are listed.
238
239Note: `toEnumCase` requires that all allowed values are unique when case insensitive.
240
241**Example: multiple options**
242```javascript
243require('ajv-keywords')(ajv, ['transform']);
244
245var schema = {
246 type: 'array',
247 items: {
248 type:'string',
249 transform:['trim','toLowerCase']
250 }
251};
252
253var data = [' MixCase '];
254ajv.validate(schema, data);
255console.log(data); // ['mixcase']
256
257```
258
259**Example: `enumcase`**
260```javascript
261require('ajv-keywords')(ajv, ['transform']);
262
263var schema = {
264 type: 'array',
265 items: {
266 type:'string',
267 transform:['trim','toEnumCase'],
268 enum:['pH']
269 }
270};
271
272var data = ['ph',' Ph','PH','pH '];
273ajv.validate(schema, data);
274console.log(data); // ['pH','pH','pH','pH']
275```
276
277
278### Keywords for arrays
279
280#### `uniqueItemProperties`
281
282The keyword allows to check that some properties in array items are unique.
283
284This keyword applies only to arrays. If the data is not an array, the validation succeeds.
285
286The value of this keyword must be an array of strings - property names that should have unique values across all items.
287
288```javascript
289var schema = { uniqueItemProperties: [ "id", "name" ] };
290
291var validData = [
292 { id: 1 },
293 { id: 2 },
294 { id: 3 }
295];
296
297var invalidData1 = [
298 { id: 1 },
299 { id: 1 }, // duplicate "id"
300 { id: 3 }
301];
302
303var invalidData2 = [
304 { id: 1, name: "taco" },
305 { id: 2, name: "taco" }, // duplicate "name"
306 { id: 3, name: "salsa" }
307];
308```
309
310This keyword is contributed by [@blainesch](https://github.com/blainesch).
311
312
313### Keywords for objects
314
315#### `allRequired`
316
317This keyword allows to require the presence of all properties used in `properties` keyword in the same schema object.
318
319This keyword applies only to objects. If the data is not an object, the validation succeeds.
320
321The value of this keyword must be boolean.
322
323If the value of the keyword is `false`, the validation succeeds.
324
325If the value of the keyword is `true`, the validation succeeds if the data contains all properties defined in `properties` keyword (in the same schema object).
326
327If the `properties` keyword is not present in the same schema object, schema compilation will throw exception.
328
329```javascript
330var schema = {
331 properties: {
332 foo: {type: 'number'},
333 bar: {type: 'number'}
334 }
335 allRequired: true
336};
337
338var validData = { foo: 1, bar: 2 };
339var alsoValidData = { foo: 1, bar: 2, baz: 3 };
340
341var invalidDataList = [ {}, { foo: 1 }, { bar: 2 } ];
342```
343
344
345#### `anyRequired`
346
347This keyword allows to require the presence of any (at least one) property from the list.
348
349This keyword applies only to objects. If the data is not an object, the validation succeeds.
350
351The value of this keyword must be an array of strings, each string being a property name. For data object to be valid at least one of the properties in this array should be present in the object.
352
353```javascript
354var schema = {
355 anyRequired: ['foo', 'bar']
356};
357
358var validData = { foo: 1 };
359var alsoValidData = { foo: 1, bar: 2 };
360
361var invalidDataList = [ {}, { baz: 3 } ];
362```
363
364
365#### `oneRequired`
366
367This keyword allows to require the presence of only one property from the list.
368
369This keyword applies only to objects. If the data is not an object, the validation succeeds.
370
371The value of this keyword must be an array of strings, each string being a property name. For data object to be valid exactly one of the properties in this array should be present in the object.
372
373```javascript
374var schema = {
375 oneRequired: ['foo', 'bar']
376};
377
378var validData = { foo: 1 };
379var alsoValidData = { bar: 2, baz: 3 };
380
381var invalidDataList = [ {}, { baz: 3 }, { foo: 1, bar: 2 } ];
382```
383
384
385#### `patternRequired`
386
387This keyword allows to require the presence of properties that match some pattern(s).
388
389This keyword applies only to objects. If the data is not an object, the validation succeeds.
390
391The value of this keyword should be an array of strings, each string being a regular expression. For data object to be valid each regular expression in this array should match at least one property name in the data object.
392
393If the array contains multiple regular expressions, more than one expression can match the same property name.
394
395```javascript
396var schema = { patternRequired: [ 'f.*o', 'b.*r' ] };
397
398var validData = { foo: 1, bar: 2 };
399var alsoValidData = { foobar: 3 };
400
401var invalidDataList = [ {}, { foo: 1 }, { bar: 2 } ];
402```
403
404
405#### `prohibited`
406
407This keyword allows to prohibit that any of the properties in the list is present in the object.
408
409This keyword applies only to objects. If the data is not an object, the validation succeeds.
410
411The value of this keyword should be an array of strings, each string being a property name. For data object to be valid none of the properties in this array should be present in the object.
412
413```
414var schema = { prohibited: ['foo', 'bar']};
415
416var validData = { baz: 1 };
417var alsoValidData = {};
418
419var invalidDataList = [
420 { foo: 1 },
421 { bar: 2 },
422 { foo: 1, bar: 2}
423];
424```
425
426__Please note__: `{prohibited: ['foo', 'bar']}` is equivalent to `{not: {anyRequired: ['foo', 'bar']}}` (i.e. it has the same validation result for any data).
427
428
429#### `deepProperties`
430
431This keyword allows to validate deep properties (identified by JSON pointers).
432
433This keyword applies only to objects. If the data is not an object, the validation succeeds.
434
435The value should be an object, where keys are JSON pointers to the data, starting from the current position in data, and the values are JSON schemas. For data object to be valid the value of each JSON pointer should be valid according to the corresponding schema.
436
437```javascript
438var schema = {
439 type: 'object',
440 deepProperties: {
441 "/users/1/role": { "enum": ["admin"] }
442 }
443};
444
445var validData = {
446 users: [
447 {},
448 {
449 id: 123,
450 role: 'admin'
451 }
452 ]
453};
454
455var alsoValidData = {
456 users: {
457 "1": {
458 id: 123,
459 role: 'admin'
460 }
461 }
462};
463
464var invalidData = {
465 users: [
466 {},
467 {
468 id: 123,
469 role: 'user'
470 }
471 ]
472};
473
474var alsoInvalidData = {
475 users: {
476 "1": {
477 id: 123,
478 role: 'user'
479 }
480 }
481};
482```
483
484
485#### `deepRequired`
486
487This keyword allows to check that some deep properties (identified by JSON pointers) are available.
488
489This keyword applies only to objects. If the data is not an object, the validation succeeds.
490
491The value should be an array of JSON pointers to the data, starting from the current position in data. For data object to be valid each JSON pointer should be some existing part of the data.
492
493```javascript
494var schema = {
495 type: 'object',
496 deepRequired: ["/users/1/role"]
497};
498
499var validData = {
500 users: [
501 {},
502 {
503 id: 123,
504 role: 'admin'
505 }
506 ]
507};
508
509var invalidData = {
510 users: [
511 {},
512 {
513 id: 123
514 }
515 ]
516};
517```
518
519See [json-schema-org/json-schema-spec#203](https://github.com/json-schema-org/json-schema-spec/issues/203#issue-197211916) for an example of the equivalent schema without `deepRequired` keyword.
520
521
522### Compound keywords
523
524#### `switch` (deprecated)
525
526__Please note__: this keyword is provided to preserve backward compatibility with previous versions of Ajv. It is strongly recommended to use `if`/`then`/`else` keywords instead, as they have been added to the draft-07 of JSON Schema specification.
527
528This keyword allows to perform advanced conditional validation.
529
530The value of the keyword is the array of if/then clauses. Each clause is the object with the following properties:
531
532- `if` (optional) - the value is JSON-schema
533- `then` (required) - the value is JSON-schema or boolean
534- `continue` (optional) - the value is boolean
535
536The validation process is dynamic; all clauses are executed sequentially in the following way:
537
5381. `if`:
539 1. `if` property is JSON-schema according to which the data is:
540 1. valid => go to step 2.
541 2. invalid => go to the NEXT clause, if this was the last clause the validation of `switch` SUCCEEDS.
542 2. `if` property is absent => go to step 2.
5432. `then`:
544 1. `then` property is `true` or it is JSON-schema according to which the data is valid => go to step 3.
545 2. `then` property is `false` or it is JSON-schema according to which the data is invalid => the validation of `switch` FAILS.
5463. `continue`:
547 1. `continue` property is `true` => go to the NEXT clause, if this was the last clause the validation of `switch` SUCCEEDS.
548 2. `continue` property is `false` or absent => validation of `switch` SUCCEEDS.
549
550```javascript
551require('ajv-keywords')(ajv, 'switch');
552
553var schema = {
554 type: 'array',
555 items: {
556 type: 'integer',
557 'switch': [
558 { if: { not: { minimum: 1 } }, then: false },
559 { if: { maximum: 10 }, then: true },
560 { if: { maximum: 100 }, then: { multipleOf: 10 } },
561 { if: { maximum: 1000 }, then: { multipleOf: 100 } },
562 { then: false }
563 ]
564 }
565};
566
567var validItems = [1, 5, 10, 20, 50, 100, 200, 500, 1000];
568
569var invalidItems = [1, 0, 2000, 11, 57, 123, 'foo'];
570```
571
572The above schema is equivalent to (for example):
573
574```javascript
575{
576 type: 'array',
577 items: {
578 type: 'integer',
579 if: { minimum: 1, maximum: 10 },
580 then: true,
581 else: {
582 if: { maximum: 100 },
583 then: { multipleOf: 10 },
584 else: {
585 if: { maximum: 1000 },
586 then: { multipleOf: 100 },
587 else: false
588 }
589 }
590 }
591}
592```
593
594
595#### `select`/`selectCases`/`selectDefault`
596
597These keywords allow to choose the schema to validate the data based on the value of some property in the validated data.
598
599These keywords must be present in the same schema object (`selectDefault` is optional).
600
601The value of `select` keyword should be a [$data reference](https://github.com/epoberezkin/ajv/tree/5.0.2-beta.0#data-reference) that points to any primitive JSON type (string, number, boolean or null) in the data that is validated. You can also use a constant of primitive type as the value of this keyword (e.g., for debugging purposes).
602
603The value of `selectCases` keyword must be an object where each property name is a possible string representation of the value of `select` keyword and each property value is a corresponding schema (from draft-06 it can be boolean) that must be used to validate the data.
604
605The value of `selectDefault` keyword is a schema (from draft-06 it can be boolean) that must be used to validate the data in case `selectCases` has no key equal to the stringified value of `select` keyword.
606
607The validation succeeds in one of the following cases:
608- the validation of data using selected schema succeeds,
609- none of the schemas is selected for validation,
610- the value of select is undefined (no property in the data that the data reference points to).
611
612If `select` value (in data) is not a primitive type the validation fails.
613
614__Please note__: these keywords require Ajv `$data` option to support [$data reference](https://github.com/epoberezkin/ajv/tree/5.0.2-beta.0#data-reference).
615
616
617```javascript
618require('ajv-keywords')(ajv, 'select');
619
620var schema = {
621 type: object,
622 required: ['kind'],
623 properties: {
624 kind: { type: 'string' }
625 },
626 select: { $data: '0/kind' },
627 selectCases: {
628 foo: {
629 required: ['foo'],
630 properties: {
631 kind: {},
632 foo: { type: 'string' }
633 },
634 additionalProperties: false
635 },
636 bar: {
637 required: ['bar'],
638 properties: {
639 kind: {},
640 bar: { type: 'number' }
641 },
642 additionalProperties: false
643 }
644 },
645 selectDefault: {
646 propertyNames: {
647 not: { enum: ['foo', 'bar'] }
648 }
649 }
650};
651
652var validDataList = [
653 { kind: 'foo', foo: 'any' },
654 { kind: 'bar', bar: 1 },
655 { kind: 'anything_else', not_bar_or_foo: 'any value' }
656];
657
658var invalidDataList = [
659 { kind: 'foo' }, // no propery foo
660 { kind: 'bar' }, // no propery bar
661 { kind: 'foo', foo: 'any', another: 'any value' }, // additional property
662 { kind: 'bar', bar: 1, another: 'any value' }, // additional property
663 { kind: 'anything_else', foo: 'any' } // property foo not allowed
664 { kind: 'anything_else', bar: 1 } // property bar not allowed
665];
666```
667
668__Please note__: the current implementation is BETA. It does not allow using relative URIs in $ref keywords in schemas in `selectCases` and `selectDefault` that point outside of these schemas. The workaround is to use absolute URIs (that can point to any (sub-)schema added to Ajv, including those inside the current root schema where `select` is used). See [tests](https://github.com/epoberezkin/ajv-keywords/blob/v2.0.0/spec/tests/select.json#L314).
669
670
671### Keywords for all types
672
673#### `dynamicDefaults`
674
675This keyword allows to assign dynamic defaults to properties, such as timestamps, unique IDs etc.
676
677This keyword only works if `useDefaults` options is used and not inside `anyOf` keywords etc., in the same way as [default keyword treated by Ajv](https://github.com/epoberezkin/ajv#assigning-defaults).
678
679The keyword should be added on the object level. Its value should be an object with each property corresponding to a property name, in the same way as in standard `properties` keyword. The value of each property can be:
680
681- an identifier of default function (a string)
682- an object with properties `func` (an identifier) and `args` (an object with parameters that will be passed to this function during schema compilation - see examples).
683
684The properties used in `dynamicDefaults` should not be added to `required` keyword (or validation will fail), because unlike `default` this keyword is processed after validation.
685
686There are several predefined dynamic default functions:
687
688- `"timestamp"` - current timestamp in milliseconds
689- `"datetime"` - current date and time as string (ISO, valid according to `date-time` format)
690- `"date"` - current date as string (ISO, valid according to `date` format)
691- `"time"` - current time as string (ISO, valid according to `time` format)
692- `"random"` - pseudo-random number in [0, 1) interval
693- `"randomint"` - pseudo-random integer number. If string is used as a property value, the function will randomly return 0 or 1. If object `{ func: 'randomint', args: { max: N } }` is used then the default will be an integer number in [0, N) interval.
694- `"seq"` - sequential integer number starting from 0. If string is used as a property value, the default sequence will be used. If object `{ func: 'seq', args: { name: 'foo'} }` is used then the sequence with name `"foo"` will be used. Sequences are global, even if different ajv instances are used.
695
696```javascript
697var schema = {
698 type: 'object',
699 dynamicDefaults: {
700 ts: 'datetime',
701 r: { func: 'randomint', args: { max: 100 } },
702 id: { func: 'seq', args: { name: 'id' } }
703 },
704 properties: {
705 ts: {
706 type: 'string',
707 format: 'date-time'
708 },
709 r: {
710 type: 'integer',
711 minimum: 0,
712 exclusiveMaximum: 100
713 },
714 id: {
715 type: 'integer',
716 minimum: 0
717 }
718 }
719};
720
721var data = {};
722ajv.validate(data); // true
723data; // { ts: '2016-12-01T22:07:28.829Z', r: 25, id: 0 }
724
725var data1 = {};
726ajv.validate(data1); // true
727data1; // { ts: '2016-12-01T22:07:29.832Z', r: 68, id: 1 }
728
729ajv.validate(data1); // true
730data1; // didn't change, as all properties were defined
731```
732
733When using the `useDefaults` option value `"empty"`, properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. Use the `allOf` [compound keyword](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) to execute `dynamicDefaults` before validation.
734
735```javascript
736var schema = {
737 allOf: [
738 {
739 dynamicDefaults: {
740 ts: 'datetime',
741 r: { func: 'randomint', args: { min: 5, max: 100 } },
742 id: { func: 'seq', args: { name: 'id' } }
743 }
744 },
745 {
746 type: 'object',
747 properties: {
748 ts: {
749 type: 'string'
750 },
751 r: {
752 type: 'number',
753 minimum: 5,
754 exclusiveMaximum: 100
755 },
756 id: {
757 type: 'integer',
758 minimum: 0
759 }
760 }
761 }
762 ]
763};
764
765var data = { ts: '', r: null };
766ajv.validate(data); // true
767data; // { ts: '2016-12-01T22:07:28.829Z', r: 25, id: 0 }
768```
769
770You can add your own dynamic default function to be recognised by this keyword:
771
772```javascript
773var uuid = require('uuid');
774
775function uuidV4() { return uuid.v4(); }
776
777var definition = require('ajv-keywords').get('dynamicDefaults').definition;
778// or require('ajv-keywords/keywords/dynamicDefaults').definition;
779definition.DEFAULTS.uuid = uuidV4;
780
781var schema = {
782 dynamicDefaults: { id: 'uuid' },
783 properties: { id: { type: 'string', format: 'uuid' } }
784};
785
786var data = {};
787ajv.validate(schema, data); // true
788data; // { id: 'a1183fbe-697b-4030-9bcc-cfeb282a9150' };
789
790var data1 = {};
791ajv.validate(schema, data1); // true
792data1; // { id: '5b008de7-1669-467a-a5c6-70fa244d7209' }
793```
794
795You also can define dynamic default that accepts parameters, e.g. version of uuid:
796
797```javascript
798var uuid = require('uuid');
799
800function getUuid(args) {
801 var version = 'v' + (arvs && args.v || 4);
802 return function() {
803 return uuid[version]();
804 };
805}
806
807var definition = require('ajv-keywords').get('dynamicDefaults').definition;
808definition.DEFAULTS.uuid = getUuid;
809
810var schema = {
811 dynamicDefaults: {
812 id1: 'uuid', // v4
813 id2: { func: 'uuid', v: 4 }, // v4
814 id3: { func: 'uuid', v: 1 } // v1
815 }
816};
817```
818
819
820## Security contact
821
822To report a security vulnerability, please use the
823[Tidelift security contact](https://tidelift.com/security).
824Tidelift will coordinate the fix and disclosure.
825
826Please do NOT report security vulnerabilities via GitHub issues.
827
828
829## Open-source software support
830
831Ajv-keywords is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv-keywords?utm_source=npm-ajv-keywords&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers.
832
833
834## License
835
836[MIT](https://github.com/epoberezkin/ajv-keywords/blob/master/LICENSE)
Note: See TracBrowser for help on using the repository browser.