web 3d图形渲染器
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

836 lines
26 KiB

  1. # ajv-keywords
  2. Custom JSON-Schema keywords for [Ajv](https://github.com/epoberezkin/ajv) validator
  3. [![Build Status](https://travis-ci.org/ajv-validator/ajv-keywords.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv-keywords)
  4. [![npm](https://img.shields.io/npm/v/ajv-keywords.svg)](https://www.npmjs.com/package/ajv-keywords)
  5. [![npm downloads](https://img.shields.io/npm/dm/ajv-keywords.svg)](https://www.npmjs.com/package/ajv-keywords)
  6. [![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)
  7. [![Dependabot](https://api.dependabot.com/badges/status?host=github&repo=ajv-validator/ajv-keywords)](https://app.dependabot.com/accounts/ajv-validator/repos/60477053)
  8. [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
  9. ## Contents
  10. - [Install](#install)
  11. - [Usage](#usage)
  12. - [Keywords](#keywords)
  13. - [Types](#types)
  14. - [typeof](#typeof)
  15. - [instanceof](#instanceof)
  16. - [Keywords for numbers](#keywords-for-numbers)
  17. - [range and exclusiveRange](#range-and-exclusiverange)
  18. - [Keywords for strings](#keywords-for-strings)
  19. - [regexp](#regexp)
  20. - [formatMaximum / formatMinimum and formatExclusiveMaximum / formatExclusiveMinimum](#formatmaximum--formatminimum-and-formatexclusivemaximum--formatexclusiveminimum)
  21. - [transform](#transform)<sup>\*</sup>
  22. - [Keywords for arrays](#keywords-for-arrays)
  23. - [uniqueItemProperties](#uniqueitemproperties)
  24. - [Keywords for objects](#keywords-for-objects)
  25. - [allRequired](#allrequired)
  26. - [anyRequired](#anyrequired)
  27. - [oneRequired](#onerequired)
  28. - [patternRequired](#patternrequired)
  29. - [prohibited](#prohibited)
  30. - [deepProperties](#deepproperties)
  31. - [deepRequired](#deeprequired)
  32. - [Compound keywords](#compound-keywords)
  33. - [switch](#switch) (deprecated)
  34. - [select/selectCases/selectDefault](#selectselectcasesselectdefault) (BETA)
  35. - [Keywords for all types](#keywords-for-all-types)
  36. - [dynamicDefaults](#dynamicdefaults)<sup>\*</sup>
  37. - [Security contact](#security-contact)
  38. - [Open-source software support](#open-source-software-support)
  39. - [License](#license)
  40. <sup>\*</sup> - keywords that modify data
  41. ## Install
  42. ```
  43. npm install ajv-keywords
  44. ```
  45. ## Usage
  46. To add all available keywords:
  47. ```javascript
  48. var Ajv = require('ajv');
  49. var ajv = new Ajv;
  50. require('ajv-keywords')(ajv);
  51. ajv.validate({ instanceof: 'RegExp' }, /.*/); // true
  52. ajv.validate({ instanceof: 'RegExp' }, '.*'); // false
  53. ```
  54. To add a single keyword:
  55. ```javascript
  56. require('ajv-keywords')(ajv, 'instanceof');
  57. ```
  58. To add multiple keywords:
  59. ```javascript
  60. require('ajv-keywords')(ajv, ['typeof', 'instanceof']);
  61. ```
  62. To add a single keyword in browser (to avoid adding unused code):
  63. ```javascript
  64. require('ajv-keywords/keywords/instanceof')(ajv);
  65. ```
  66. ## Keywords
  67. ### Types
  68. #### `typeof`
  69. Based on JavaScript `typeof` operation.
  70. The value of the keyword should be a string (`"undefined"`, `"string"`, `"number"`, `"object"`, `"function"`, `"boolean"` or `"symbol"`) or array of strings.
  71. To pass validation the result of `typeof` operation on the value should be equal to the string (or one of the strings in the array).
  72. ```
  73. ajv.validate({ typeof: 'undefined' }, undefined); // true
  74. ajv.validate({ typeof: 'undefined' }, null); // false
  75. ajv.validate({ typeof: ['undefined', 'object'] }, null); // true
  76. ```
  77. #### `instanceof`
  78. Based on JavaScript `instanceof` operation.
  79. The value of the keyword should be a string (`"Object"`, `"Array"`, `"Function"`, `"Number"`, `"String"`, `"Date"`, `"RegExp"`, `"Promise"` or `"Buffer"`) or array of strings.
  80. To pass validation the result of `data instanceof ...` operation on the value should be true:
  81. ```
  82. ajv.validate({ instanceof: 'Array' }, []); // true
  83. ajv.validate({ instanceof: 'Array' }, {}); // false
  84. ajv.validate({ instanceof: ['Array', 'Function'] }, function(){}); // true
  85. ```
  86. You can add your own constructor function to be recognised by this keyword:
  87. ```javascript
  88. function MyClass() {}
  89. var instanceofDefinition = require('ajv-keywords').get('instanceof').definition;
  90. // or require('ajv-keywords/keywords/instanceof').definition;
  91. instanceofDefinition.CONSTRUCTORS.MyClass = MyClass;
  92. ajv.validate({ instanceof: 'MyClass' }, new MyClass); // true
  93. ```
  94. ### Keywords for numbers
  95. #### `range` and `exclusiveRange`
  96. Syntax sugar for the combination of minimum and maximum keywords, also fails schema compilation if there are no numbers in the range.
  97. The value of this keyword must be the array consisting of two numbers, the second must be greater or equal than the first one.
  98. If 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.
  99. ```javascript
  100. var schema = { range: [1, 3] };
  101. ajv.validate(schema, 1); // true
  102. ajv.validate(schema, 2); // true
  103. ajv.validate(schema, 3); // true
  104. ajv.validate(schema, 0.99); // false
  105. ajv.validate(schema, 3.01); // false
  106. var schema = { range: [1, 3], exclusiveRange: true };
  107. ajv.validate(schema, 1.01); // true
  108. ajv.validate(schema, 2); // true
  109. ajv.validate(schema, 2.99); // true
  110. ajv.validate(schema, 1); // false
  111. ajv.validate(schema, 3); // false
  112. ```
  113. ### Keywords for strings
  114. #### `regexp`
  115. This keyword allows to use regular expressions with flags in schemas (the standard `pattern` keyword does not support flags).
  116. This keyword applies only to strings. If the data is not a string, the validation succeeds.
  117. The 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).
  118. ```javascript
  119. var schema = {
  120. type: 'object',
  121. properties: {
  122. foo: { regexp: '/foo/i' },
  123. bar: { regexp: { pattern: 'bar', flags: 'i' } }
  124. }
  125. };
  126. var validData = {
  127. foo: 'Food',
  128. bar: 'Barmen'
  129. };
  130. var invalidData = {
  131. foo: 'fog',
  132. bar: 'bad'
  133. };
  134. ```
  135. #### `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum`
  136. These keywords allow to define minimum/maximum constraints when the format keyword defines ordering.
  137. These keywords apply only to strings. If the data is not a string, the validation succeeds.
  138. The 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.
  139. When 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.
  140. The 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.
  141. ```javascript
  142. require('ajv-keywords')(ajv, ['formatMinimum', 'formatMaximum']);
  143. var schema = {
  144. format: 'date',
  145. formatMinimum: '2016-02-06',
  146. formatMaximum: '2016-12-27',
  147. formatExclusiveMaximum: true
  148. }
  149. var validDataList = ['2016-02-06', '2016-12-26', 1];
  150. var invalidDataList = ['2016-02-05', '2016-12-27', 'abc'];
  151. ```
  152. #### `transform`
  153. This keyword allows a string to be modified before validation.
  154. These keywords apply only to strings. If the data is not a string, the transform is skipped.
  155. There are limitation due to how ajv is written:
  156. - a stand alone string cannot be transformed. ie `data = 'a'; ajv.validate(schema, data);`
  157. - currently cannot work with `ajv-pack`
  158. **Supported options:**
  159. - `trim`: remove whitespace from start and end
  160. - `trimLeft`: remove whitespace from start
  161. - `trimRight`: remove whitespace from end
  162. - `toLowerCase`: case string to all lower case
  163. - `toUpperCase`: case string to all upper case
  164. - `toEnumCase`: case string to match case in schema
  165. Options are applied in the order they are listed.
  166. Note: `toEnumCase` requires that all allowed values are unique when case insensitive.
  167. **Example: multiple options**
  168. ```javascript
  169. require('ajv-keywords')(ajv, ['transform']);
  170. var schema = {
  171. type: 'array',
  172. items: {
  173. type:'string',
  174. transform:['trim','toLowerCase']
  175. }
  176. };
  177. var data = [' MixCase '];
  178. ajv.validate(schema, data);
  179. console.log(data); // ['mixcase']
  180. ```
  181. **Example: `enumcase`**
  182. ```javascript
  183. require('ajv-keywords')(ajv, ['transform']);
  184. var schema = {
  185. type: 'array',
  186. items: {
  187. type:'string',
  188. transform:['trim','toEnumCase'],
  189. enum:['pH']
  190. }
  191. };
  192. var data = ['ph',' Ph','PH','pH '];
  193. ajv.validate(schema, data);
  194. console.log(data); // ['pH','pH','pH','pH']
  195. ```
  196. ### Keywords for arrays
  197. #### `uniqueItemProperties`
  198. The keyword allows to check that some properties in array items are unique.
  199. This keyword applies only to arrays. If the data is not an array, the validation succeeds.
  200. The value of this keyword must be an array of strings - property names that should have unique values across all items.
  201. ```javascript
  202. var schema = { uniqueItemProperties: [ "id", "name" ] };
  203. var validData = [
  204. { id: 1 },
  205. { id: 2 },
  206. { id: 3 }
  207. ];
  208. var invalidData1 = [
  209. { id: 1 },
  210. { id: 1 }, // duplicate "id"
  211. { id: 3 }
  212. ];
  213. var invalidData2 = [
  214. { id: 1, name: "taco" },
  215. { id: 2, name: "taco" }, // duplicate "name"
  216. { id: 3, name: "salsa" }
  217. ];
  218. ```
  219. This keyword is contributed by [@blainesch](https://github.com/blainesch).
  220. ### Keywords for objects
  221. #### `allRequired`
  222. This keyword allows to require the presence of all properties used in `properties` keyword in the same schema object.
  223. This keyword applies only to objects. If the data is not an object, the validation succeeds.
  224. The value of this keyword must be boolean.
  225. If the value of the keyword is `false`, the validation succeeds.
  226. If 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).
  227. If the `properties` keyword is not present in the same schema object, schema compilation will throw exception.
  228. ```javascript
  229. var schema = {
  230. properties: {
  231. foo: {type: 'number'},
  232. bar: {type: 'number'}
  233. }
  234. allRequired: true
  235. };
  236. var validData = { foo: 1, bar: 2 };
  237. var alsoValidData = { foo: 1, bar: 2, baz: 3 };
  238. var invalidDataList = [ {}, { foo: 1 }, { bar: 2 } ];
  239. ```
  240. #### `anyRequired`
  241. This keyword allows to require the presence of any (at least one) property from the list.
  242. This keyword applies only to objects. If the data is not an object, the validation succeeds.
  243. The 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.
  244. ```javascript
  245. var schema = {
  246. anyRequired: ['foo', 'bar']
  247. };
  248. var validData = { foo: 1 };
  249. var alsoValidData = { foo: 1, bar: 2 };
  250. var invalidDataList = [ {}, { baz: 3 } ];
  251. ```
  252. #### `oneRequired`
  253. This keyword allows to require the presence of only one property from the list.
  254. This keyword applies only to objects. If the data is not an object, the validation succeeds.
  255. The 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.
  256. ```javascript
  257. var schema = {
  258. oneRequired: ['foo', 'bar']
  259. };
  260. var validData = { foo: 1 };
  261. var alsoValidData = { bar: 2, baz: 3 };
  262. var invalidDataList = [ {}, { baz: 3 }, { foo: 1, bar: 2 } ];
  263. ```
  264. #### `patternRequired`
  265. This keyword allows to require the presence of properties that match some pattern(s).
  266. This keyword applies only to objects. If the data is not an object, the validation succeeds.
  267. The 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.
  268. If the array contains multiple regular expressions, more than one expression can match the same property name.
  269. ```javascript
  270. var schema = { patternRequired: [ 'f.*o', 'b.*r' ] };
  271. var validData = { foo: 1, bar: 2 };
  272. var alsoValidData = { foobar: 3 };
  273. var invalidDataList = [ {}, { foo: 1 }, { bar: 2 } ];
  274. ```
  275. #### `prohibited`
  276. This keyword allows to prohibit that any of the properties in the list is present in the object.
  277. This keyword applies only to objects. If the data is not an object, the validation succeeds.
  278. The 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.
  279. ```
  280. var schema = { prohibited: ['foo', 'bar']};
  281. var validData = { baz: 1 };
  282. var alsoValidData = {};
  283. var invalidDataList = [
  284. { foo: 1 },
  285. { bar: 2 },
  286. { foo: 1, bar: 2}
  287. ];
  288. ```
  289. __Please note__: `{prohibited: ['foo', 'bar']}` is equivalent to `{not: {anyRequired: ['foo', 'bar']}}` (i.e. it has the same validation result for any data).
  290. #### `deepProperties`
  291. This keyword allows to validate deep properties (identified by JSON pointers).
  292. This keyword applies only to objects. If the data is not an object, the validation succeeds.
  293. The 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.
  294. ```javascript
  295. var schema = {
  296. type: 'object',
  297. deepProperties: {
  298. "/users/1/role": { "enum": ["admin"] }
  299. }
  300. };
  301. var validData = {
  302. users: [
  303. {},
  304. {
  305. id: 123,
  306. role: 'admin'
  307. }
  308. ]
  309. };
  310. var alsoValidData = {
  311. users: {
  312. "1": {
  313. id: 123,
  314. role: 'admin'
  315. }
  316. }
  317. };
  318. var invalidData = {
  319. users: [
  320. {},
  321. {
  322. id: 123,
  323. role: 'user'
  324. }
  325. ]
  326. };
  327. var alsoInvalidData = {
  328. users: {
  329. "1": {
  330. id: 123,
  331. role: 'user'
  332. }
  333. }
  334. };
  335. ```
  336. #### `deepRequired`
  337. This keyword allows to check that some deep properties (identified by JSON pointers) are available.
  338. This keyword applies only to objects. If the data is not an object, the validation succeeds.
  339. The 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.
  340. ```javascript
  341. var schema = {
  342. type: 'object',
  343. deepRequired: ["/users/1/role"]
  344. };
  345. var validData = {
  346. users: [
  347. {},
  348. {
  349. id: 123,
  350. role: 'admin'
  351. }
  352. ]
  353. };
  354. var invalidData = {
  355. users: [
  356. {},
  357. {
  358. id: 123
  359. }
  360. ]
  361. };
  362. ```
  363. See [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.
  364. ### Compound keywords
  365. #### `switch` (deprecated)
  366. __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.
  367. This keyword allows to perform advanced conditional validation.
  368. The value of the keyword is the array of if/then clauses. Each clause is the object with the following properties:
  369. - `if` (optional) - the value is JSON-schema
  370. - `then` (required) - the value is JSON-schema or boolean
  371. - `continue` (optional) - the value is boolean
  372. The validation process is dynamic; all clauses are executed sequentially in the following way:
  373. 1. `if`:
  374. 1. `if` property is JSON-schema according to which the data is:
  375. 1. valid => go to step 2.
  376. 2. invalid => go to the NEXT clause, if this was the last clause the validation of `switch` SUCCEEDS.
  377. 2. `if` property is absent => go to step 2.
  378. 2. `then`:
  379. 1. `then` property is `true` or it is JSON-schema according to which the data is valid => go to step 3.
  380. 2. `then` property is `false` or it is JSON-schema according to which the data is invalid => the validation of `switch` FAILS.
  381. 3. `continue`:
  382. 1. `continue` property is `true` => go to the NEXT clause, if this was the last clause the validation of `switch` SUCCEEDS.
  383. 2. `continue` property is `false` or absent => validation of `switch` SUCCEEDS.
  384. ```javascript
  385. require('ajv-keywords')(ajv, 'switch');
  386. var schema = {
  387. type: 'array',
  388. items: {
  389. type: 'integer',
  390. 'switch': [
  391. { if: { not: { minimum: 1 } }, then: false },
  392. { if: { maximum: 10 }, then: true },
  393. { if: { maximum: 100 }, then: { multipleOf: 10 } },
  394. { if: { maximum: 1000 }, then: { multipleOf: 100 } },
  395. { then: false }
  396. ]
  397. }
  398. };
  399. var validItems = [1, 5, 10, 20, 50, 100, 200, 500, 1000];
  400. var invalidItems = [1, 0, 2000, 11, 57, 123, 'foo'];
  401. ```
  402. The above schema is equivalent to (for example):
  403. ```javascript
  404. {
  405. type: 'array',
  406. items: {
  407. type: 'integer',
  408. if: { minimum: 1, maximum: 10 },
  409. then: true,
  410. else: {
  411. if: { maximum: 100 },
  412. then: { multipleOf: 10 },
  413. else: {
  414. if: { maximum: 1000 },
  415. then: { multipleOf: 100 },
  416. else: false
  417. }
  418. }
  419. }
  420. }
  421. ```
  422. #### `select`/`selectCases`/`selectDefault`
  423. These keywords allow to choose the schema to validate the data based on the value of some property in the validated data.
  424. These keywords must be present in the same schema object (`selectDefault` is optional).
  425. The 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).
  426. The 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.
  427. The 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.
  428. The validation succeeds in one of the following cases:
  429. - the validation of data using selected schema succeeds,
  430. - none of the schemas is selected for validation,
  431. - the value of select is undefined (no property in the data that the data reference points to).
  432. If `select` value (in data) is not a primitive type the validation fails.
  433. __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).
  434. ```javascript
  435. require('ajv-keywords')(ajv, 'select');
  436. var schema = {
  437. type: object,
  438. required: ['kind'],
  439. properties: {
  440. kind: { type: 'string' }
  441. },
  442. select: { $data: '0/kind' },
  443. selectCases: {
  444. foo: {
  445. required: ['foo'],
  446. properties: {
  447. kind: {},
  448. foo: { type: 'string' }
  449. },
  450. additionalProperties: false
  451. },
  452. bar: {
  453. required: ['bar'],
  454. properties: {
  455. kind: {},
  456. bar: { type: 'number' }
  457. },
  458. additionalProperties: false
  459. }
  460. },
  461. selectDefault: {
  462. propertyNames: {
  463. not: { enum: ['foo', 'bar'] }
  464. }
  465. }
  466. };
  467. var validDataList = [
  468. { kind: 'foo', foo: 'any' },
  469. { kind: 'bar', bar: 1 },
  470. { kind: 'anything_else', not_bar_or_foo: 'any value' }
  471. ];
  472. var invalidDataList = [
  473. { kind: 'foo' }, // no propery foo
  474. { kind: 'bar' }, // no propery bar
  475. { kind: 'foo', foo: 'any', another: 'any value' }, // additional property
  476. { kind: 'bar', bar: 1, another: 'any value' }, // additional property
  477. { kind: 'anything_else', foo: 'any' } // property foo not allowed
  478. { kind: 'anything_else', bar: 1 } // property bar not allowed
  479. ];
  480. ```
  481. __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).
  482. ### Keywords for all types
  483. #### `dynamicDefaults`
  484. This keyword allows to assign dynamic defaults to properties, such as timestamps, unique IDs etc.
  485. This 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).
  486. The 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:
  487. - an identifier of default function (a string)
  488. - 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).
  489. 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.
  490. There are several predefined dynamic default functions:
  491. - `"timestamp"` - current timestamp in milliseconds
  492. - `"datetime"` - current date and time as string (ISO, valid according to `date-time` format)
  493. - `"date"` - current date as string (ISO, valid according to `date` format)
  494. - `"time"` - current time as string (ISO, valid according to `time` format)
  495. - `"random"` - pseudo-random number in [0, 1) interval
  496. - `"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.
  497. - `"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.
  498. ```javascript
  499. var schema = {
  500. type: 'object',
  501. dynamicDefaults: {
  502. ts: 'datetime',
  503. r: { func: 'randomint', args: { max: 100 } },
  504. id: { func: 'seq', args: { name: 'id' } }
  505. },
  506. properties: {
  507. ts: {
  508. type: 'string',
  509. format: 'date-time'
  510. },
  511. r: {
  512. type: 'integer',
  513. minimum: 0,
  514. exclusiveMaximum: 100
  515. },
  516. id: {
  517. type: 'integer',
  518. minimum: 0
  519. }
  520. }
  521. };
  522. var data = {};
  523. ajv.validate(data); // true
  524. data; // { ts: '2016-12-01T22:07:28.829Z', r: 25, id: 0 }
  525. var data1 = {};
  526. ajv.validate(data1); // true
  527. data1; // { ts: '2016-12-01T22:07:29.832Z', r: 68, id: 1 }
  528. ajv.validate(data1); // true
  529. data1; // didn't change, as all properties were defined
  530. ```
  531. When 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.
  532. ```javascript
  533. var schema = {
  534. allOf: [
  535. {
  536. dynamicDefaults: {
  537. ts: 'datetime',
  538. r: { func: 'randomint', args: { min: 5, max: 100 } },
  539. id: { func: 'seq', args: { name: 'id' } }
  540. }
  541. },
  542. {
  543. type: 'object',
  544. properties: {
  545. ts: {
  546. type: 'string'
  547. },
  548. r: {
  549. type: 'number',
  550. minimum: 5,
  551. exclusiveMaximum: 100
  552. },
  553. id: {
  554. type: 'integer',
  555. minimum: 0
  556. }
  557. }
  558. }
  559. ]
  560. };
  561. var data = { ts: '', r: null };
  562. ajv.validate(data); // true
  563. data; // { ts: '2016-12-01T22:07:28.829Z', r: 25, id: 0 }
  564. ```
  565. You can add your own dynamic default function to be recognised by this keyword:
  566. ```javascript
  567. var uuid = require('uuid');
  568. function uuidV4() { return uuid.v4(); }
  569. var definition = require('ajv-keywords').get('dynamicDefaults').definition;
  570. // or require('ajv-keywords/keywords/dynamicDefaults').definition;
  571. definition.DEFAULTS.uuid = uuidV4;
  572. var schema = {
  573. dynamicDefaults: { id: 'uuid' },
  574. properties: { id: { type: 'string', format: 'uuid' } }
  575. };
  576. var data = {};
  577. ajv.validate(schema, data); // true
  578. data; // { id: 'a1183fbe-697b-4030-9bcc-cfeb282a9150' };
  579. var data1 = {};
  580. ajv.validate(schema, data1); // true
  581. data1; // { id: '5b008de7-1669-467a-a5c6-70fa244d7209' }
  582. ```
  583. You also can define dynamic default that accepts parameters, e.g. version of uuid:
  584. ```javascript
  585. var uuid = require('uuid');
  586. function getUuid(args) {
  587. var version = 'v' + (arvs && args.v || 4);
  588. return function() {
  589. return uuid[version]();
  590. };
  591. }
  592. var definition = require('ajv-keywords').get('dynamicDefaults').definition;
  593. definition.DEFAULTS.uuid = getUuid;
  594. var schema = {
  595. dynamicDefaults: {
  596. id1: 'uuid', // v4
  597. id2: { func: 'uuid', v: 4 }, // v4
  598. id3: { func: 'uuid', v: 1 } // v1
  599. }
  600. };
  601. ```
  602. ## Security contact
  603. To report a security vulnerability, please use the
  604. [Tidelift security contact](https://tidelift.com/security).
  605. Tidelift will coordinate the fix and disclosure.
  606. Please do NOT report security vulnerabilities via GitHub issues.
  607. ## Open-source software support
  608. Ajv-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.
  609. ## License
  610. [MIT](https://github.com/epoberezkin/ajv-keywords/blob/master/LICENSE)