arnaucube
arnaucube/thoughtsPublic Self-hosted repository
thoughts/node_modules/jsonwebtoken/node_modules/joi/API.md
node_modules/jsonwebtoken/node_modules/joi/API.mdRaw
   1<!-- version -->
   2# 6.10.1 API Reference
   3<!-- versionstop -->
   4
   5<img src="https://raw.github.com/hapijs/joi/master/images/validation.png" align="right" />
   6
   7<!-- toc -->
   8
   9- [Joi](#joi)
  10  - [`validate(value, schema, [options], [callback])`](#validatevalue-schema-options-callback)
  11  - [`compile(schema)`](#compileschema)
  12  - [`assert(value, schema, [message])`](#assertvalue-schema-message)
  13  - [`attempt(value, schema, [message])`](#attemptvalue-schema-message)
  14  - [`isRef(ref)`](#isrefref)
  15  - [`any`](#any)
  16    - [`any.allow(value)`](#anyallowvalue)
  17    - [`any.valid(value)` - aliases: `only`, `equal`](#anyvalidvalue---aliases-only-equal)
  18    - [`any.invalid(value)` - aliases: `disallow`, `not`](#anyinvalidvalue---aliases-disallow-not)
  19    - [`any.required()`](#anyrequired)
  20    - [`any.optional()`](#anyoptional)
  21    - [`any.forbidden()`](#anyforbidden)
  22    - [`any.strip()`](#anystrip)
  23    - [`any.description(desc)`](#anydescriptiondesc)
  24    - [`any.notes(notes)`](#anynotesnotes)
  25    - [`any.tags(tags)`](#anytagstags)
  26    - [`any.meta(meta)`](#anymetameta)
  27    - [`any.example(value)`](#anyexamplevalue)
  28    - [`any.unit(name)`](#anyunitname)
  29    - [`any.options(options)`](#anyoptionsoptions)
  30    - [`any.strict(isStrict)`](#anystrictisstrict)
  31    - [`any.default([value, [description]])`](#anydefaultvalue-description)
  32    - [`any.concat(schema)`](#anyconcatschema)
  33    - [`any.when(ref, options)`](#anywhenref-options)
  34    - [`any.label(name)`](#anylabelname)
  35    - [`any.raw(isRaw)`](#anyrawisraw)
  36    - [`any.empty(schema)`](#anyemptyschema)
  37  - [`array`](#array)
  38    - [`array.sparse(enabled)`](#arraysparseenabled)
  39    - [`array.single(enabled)`](#arraysingleenabled)
  40    - [`array.items(type)`](#arrayitemstype)
  41    - [`array.ordered(type)`](#arrayorderedtype)
  42    - [`array.min(limit)`](#arrayminlimit)
  43    - [`array.max(limit)`](#arraymaxlimit)
  44    - [`array.length(limit)`](#arraylengthlimit)
  45    - [`array.unique()`](#arrayunique)
  46  - [`boolean`](#boolean)
  47  - [`binary`](#binary)
  48    - [`binary.encoding(encoding)`](#binaryencodingencoding)
  49    - [`binary.min(limit)`](#binaryminlimit)
  50    - [`binary.max(limit)`](#binarymaxlimit)
  51    - [`binary.length(limit)`](#binarylengthlimit)
  52  - [`date`](#date)
  53    - [`date.min(date)`](#datemindate)
  54    - [`date.max(date)`](#datemaxdate)
  55    - [`date.format(format)`](#dateformatformat)
  56    - [`date.iso()`](#dateiso)
  57  - [`func`](#func)
  58  - [`number`](#number)
  59    - [`number.min(limit)`](#numberminlimit)
  60    - [`number.max(limit)`](#numbermaxlimit)
  61    - [`number.greater(limit)`](#numbergreaterlimit)
  62    - [`number.less(limit)`](#numberlesslimit)
  63    - [`number.integer()`](#numberinteger)
  64    - [`number.precision(limit)`](#numberprecisionlimit)
  65    - [`number.multiple(base)`](#numbermultiplebase)
  66    - [`number.positive()`](#numberpositive)
  67    - [`number.negative()`](#numbernegative)
  68  - [`object`](#object)
  69    - [`object.keys([schema])`](#objectkeysschema)
  70      - [`{} notation`](#-notation)
  71      - [`Joi.object([schema]) notation`](#joiobjectschema-notation)
  72      - [`Joi.object().keys([schema]) notation`](#joiobjectkeysschema-notation)
  73    - [`object.min(limit)`](#objectminlimit)
  74    - [`object.max(limit)`](#objectmaxlimit)
  75    - [`object.length(limit)`](#objectlengthlimit)
  76    - [`object.pattern(regex, schema)`](#objectpatternregex-schema)
  77    - [`object.and(peers)`](#objectandpeers)
  78    - [`object.nand(peers)`](#objectnandpeers)
  79    - [`object.or(peers)`](#objectorpeers)
  80    - [`object.xor(peers)`](#objectxorpeers)
  81    - [`object.with(key, peers)`](#objectwithkey-peers)
  82    - [`object.without(key, peers)`](#objectwithoutkey-peers)
  83    - [`object.rename(from, to, [options])`](#objectrenamefrom-to-options)
  84    - [`object.assert(ref, schema, [message])`](#objectassertref-schema-message)
  85    - [`object.unknown([allow])`](#objectunknownallow)
  86    - [`object.type(constructor, [name])`](#objecttypeconstructor-name)
  87    - [`object.requiredKeys(children)`](#objectrequiredkeyschildren)
  88    - [`object.optionalKeys(children)`](#objectoptionalkeyschildren)
  89  - [`string`](#string)
  90    - [`string.insensitive()`](#stringinsensitive)
  91    - [`string.min(limit, [encoding])`](#stringminlimit-encoding)
  92    - [`string.max(limit, [encoding])`](#stringmaxlimit-encoding)
  93    - [`string.creditCard()`](#stringcreditcard)
  94    - [`string.length(limit, [encoding])`](#stringlengthlimit-encoding)
  95    - [`string.regex(pattern, [name])`](#stringregexpattern-name)
  96    - [`string.replace(pattern, replacement)`](#stringreplacepattern-replacement)
  97    - [`string.alphanum()`](#stringalphanum)
  98    - [`string.token()`](#stringtoken)
  99    - [`string.email([options])`](#stringemailoptions)
 100    - [`string.ip([options])`](#stringipoptions)
 101    - [`string.uri([options])`](#stringurioptions)
 102    - [`string.guid()`](#stringguid)
 103    - [`string.hex()`](#stringhex)
 104    - [`string.hostname()`](#stringhostname)
 105    - [`string.lowercase()`](#stringlowercase)
 106    - [`string.uppercase()`](#stringuppercase)
 107    - [`string.trim()`](#stringtrim)
 108    - [`string.isoDate()`](#stringisodate)
 109  - [`alternatives`](#alternatives)
 110    - [`alternatives.try(schemas)`](#alternativestryschemas)
 111    - [`alternatives.when(ref, options)`](#alternativeswhenref-options)
 112  - [`ref(key, [options])`](#refkey-options)
 113- [Errors](#errors)
 114
 115<!-- tocstop -->
 116
 117## Joi
 118
 119### `validate(value, schema, [options], [callback])`
 120
 121Validates a value using the given schema and options where:
 122- `value` - the value being validated.
 123- `schema` - the validation schema. Can be a **joi** type object or a plain object where every key is assigned a **joi** type object.
 124- `options` - an optional object with the following optional keys:
 125  - `abortEarly` - when `true`, stops validation on the first error, otherwise returns all the errors found. Defaults to `true`.
 126  - `convert` - when `true`, attempts to cast values to the required types (e.g. a string to a number). Defaults to `true`.
 127  - `allowUnknown` - when `true`, allows object to contain unknown keys which are ignored. Defaults to `false`.
 128  - `skipFunctions` - when `true`, ignores unknown keys with a function value. Defaults to `false`.
 129  - `stripUnknown` - when `true`, unknown keys are deleted (only when value is an object or an array). Defaults to `false`.
 130  - `language` - overrides individual error messages, when `'label'` is set, it overrides the key name in the error message. Defaults to no override (`{}`).
 131  - `presence` - sets the default presence requirements. Supported modes: `'optional'`, `'required'`, and `'forbidden'`.
 132    Defaults to `'optional'`.
 133  - `context` - provides an external data set to be used in [references](#refkey-options). Can only be set as an external option to
 134    `validate()` and not using `any.options()`.
 135  - `noDefaults` - when `true`, do not apply default values. Defaults to `false`.
 136- `callback` - the optional synchronous callback method using the signature `function(err, value)` where:
 137  - `err` - if validation failed, the [error](#errors) reason, otherwise `null`.
 138  - `value` - the validated value with any type conversions and other modifiers applied (the input is left unchanged). `value` can be
 139    incomplete if validation failed and `abortEarly` is `true`. If callback is not provided, then returns an object with [error](#errors)
 140    and value properties.
 141
 142```javascript
 143var schema = {
 144    a: Joi.number()
 145};
 146
 147var value = {
 148    a: '123'
 149};
 150
 151Joi.validate(value, schema, function (err, value) { });
 152// err -> null
 153// value.a -> 123 (number, not string)
 154
 155// or
 156var result = Joi.validate(value, schema);
 157// result.error -> null
 158// result.value -> { "a" : 123 }
 159```
 160
 161### `compile(schema)`
 162
 163Converts literal schema definition to **joi** schema object (or returns the same back if already a **joi** schema object) where:
 164- `schema` - the schema definition to compile.
 165
 166```javascript
 167var definition = ['key', 5, { a: true, b: [/^a/, 'boom'] }];
 168var schema = Joi.compile(definition);
 169
 170// Same as:
 171
 172var schema = Joi.alternatives().try([
 173    Joi.string().valid('key'),
 174    Joi.number().valid(5),
 175    Joi.object().keys({
 176        a: Joi.boolean().valid(true),
 177        b: Joi.alternatives().try([
 178            Joi.string().regex(/^a/),
 179            Joi.string().valid('boom')
 180        ])
 181    })
 182]);
 183```
 184
 185### `assert(value, schema, [message])`
 186
 187Validates a value against a schema and [throws](#errors) if validation fails where:
 188- `value` - the value to validate.
 189- `schema` - the schema object.
 190- `message` - optional message string prefix added in front of the error message. may also be an Error object.
 191
 192```javascript
 193Joi.assert('x', Joi.number());
 194```
 195
 196### `attempt(value, schema, [message])`
 197
 198Validates a value against a schema, returns valid object, and [throws](#errors) if validation fails where:
 199- `value` - the value to validate.
 200- `schema` - the schema object.
 201- `message` - optional message string prefix added in front of the error message. may also be an Error object.
 202
 203```javascript
 204Joi.attempt('x', Joi.number()); // throws error
 205var result = Joi.attempt('4', Joi.number()); // result -> 4
 206```
 207
 208### `isRef(ref)`
 209
 210Checks whether or not the provided argument is a reference.
 211It's especially useful if you want to post-process error messages.
 212
 213```js
 214var ref = Joi.ref('a');
 215Joi.isRef(ref); // returns true
 216```
 217
 218### `any`
 219
 220Generates a schema object that matches any data type.
 221
 222```javascript
 223var any = Joi.any();
 224any.validate('a', function (err, value) { });
 225```
 226
 227#### `any.allow(value)`
 228
 229Whitelists a value where:
 230- `value` - the allowed value which can be of any type and will be matched against the validated value before applying any other rules.
 231  `value` can be an array of values, or multiple values can be passed as individual arguments. `value` supports [references](#refkey-options).
 232
 233Note that this whitelist of allowed values is in *addition* to any other permitted values.
 234To create an exclusive whitelist of values, see [`any.valid(value)`](#anyvalidvalue).
 235
 236```javascript
 237var schema = {
 238    a: Joi.any().allow('a'),
 239    b: Joi.any().allow('b', 'B'),
 240    c: Joi.any().allow(['c', 'C'])
 241};
 242```
 243
 244#### `any.valid(value)` - aliases: `only`, `equal`
 245
 246Adds the provided values into the allowed whitelist and marks them as the only valid values allowed where:
 247- `value` - the allowed value which can be of any type and will be matched against the validated value before applying any other rules.
 248  `value` can be an array of values, or multiple values can be passed as individual arguments. `value` supports [references](#refkey-options).
 249
 250```javascript
 251var schema = {
 252    a: Joi.any().valid('a'),
 253    b: Joi.any().valid('b', 'B'),
 254    c: Joi.any().valid(['c', 'C'])
 255};
 256```
 257
 258#### `any.invalid(value)` - aliases: `disallow`, `not`
 259
 260Blacklists a value where:
 261- `value` - the forbidden value which can be of any type and will be matched against the validated value before applying any other rules.
 262  `value` can be an array of values, or multiple values can be passed as individual arguments. `value` supports [references](#refkey-options).
 263
 264```javascript
 265var schema = {
 266    a: Joi.any().invalid('a'),
 267    b: Joi.any().invalid('b', 'B'),
 268    c: Joi.any().invalid(['c', 'C'])
 269};
 270```
 271
 272#### `any.required()`
 273
 274Marks a key as required which will not allow `undefined` as value. All keys are optional by default.
 275
 276```javascript
 277var schema = Joi.any().required();
 278```
 279
 280#### `any.optional()`
 281
 282Marks a key as optional which will allow `undefined` as values. Used to annotate the schema for readability as all keys are optional by default.
 283
 284```javascript
 285var schema = Joi.any().optional();
 286```
 287
 288#### `any.forbidden()`
 289
 290Marks a key as forbidden which will not allow any value except `undefined`. Used to explicitly forbid keys.
 291
 292```javascript
 293var schema = {
 294    a: Joi.any().forbidden()
 295};
 296```
 297
 298#### `any.strip()`
 299
 300Marks a key to be removed from a resulting object or array after validation. Used to sanitize output.
 301
 302```javascript
 303var schema = {
 304    username: Joi.string(),
 305    password: Joi.string().strip()
 306};
 307
 308schema.validate({ username: 'test', password: 'hunter2' }, function (err, value) {
 309    // value = { username: 'test' }
 310});
 311
 312var schema = Joi.array().items(Joi.string(), Joi.any().strip());
 313
 314schema.validate(['one', 'two', true, false, 1, 2], function (err, value) {
 315    // value = ['one', 'two']
 316});
 317```
 318
 319#### `any.description(desc)`
 320
 321Annotates the key where:
 322- `desc` - the description string.
 323
 324```javascript
 325var schema = Joi.any().description('this key will match anything you give it');
 326```
 327
 328#### `any.notes(notes)`
 329
 330Annotates the key where:
 331- `notes` - the notes string or array of strings.
 332
 333```javascript
 334var schema = Joi.any().notes(['this is special', 'this is important']);
 335```
 336
 337#### `any.tags(tags)`
 338
 339Annotates the key where:
 340- `tags` - the tag string or array of strings.
 341
 342```javascript
 343var schema = Joi.any().tags(['api', 'user']);
 344```
 345
 346#### `any.meta(meta)`
 347
 348Attaches metadata to the key where:
 349- `meta` - the meta object to attach.
 350
 351```javascript
 352var schema = Joi.any().meta({ index: true });
 353```
 354
 355#### `any.example(value)`
 356
 357Annotates the key where:
 358- `value` - an example value.
 359
 360If the example fails to pass validation, the function will throw.
 361
 362```javascript
 363var schema = Joi.string().min(4).example('abcd');
 364```
 365
 366#### `any.unit(name)`
 367
 368Annotates the key where:
 369- `name` - the unit name of the value.
 370
 371```javascript
 372var schema = Joi.number().unit('milliseconds');
 373```
 374
 375#### `any.options(options)`
 376
 377Overrides the global `validate()` options for the current key and any sub-key where:
 378- `options` - an object with the same optional keys as [`Joi.validate(value, schema, options, callback)`](#validatevalue-schema-options-callback).
 379
 380```javascript
 381var schema = Joi.any().options({ convert: false });
 382```
 383
 384#### `any.strict(isStrict)`
 385
 386Strict mode sets the `options.convert` options to `false` which prevent type casting for the current key and any child keys.
 387- `isStrict` - whether strict mode is enabled or not. Defaults to true.
 388
 389```javascript
 390var schema = Joi.any().strict();
 391```
 392
 393#### `any.default([value, [description]])`
 394
 395Sets a default value if the original value is undefined where:
 396- `value` - the value.
 397  - `value` supports [references](#refkey-options).
 398  - `value` may also be a function which returns the default value. If `value` is specified as a function that accepts a single parameter, that parameter will be a context object that can be used to derive the resulting value. **This clones the object however, which incurs some overhead so if you don't need access to the context define your method so that it does not accept any parameters**.
 399  - without any `value`, `default` has no effect, except for `object` that will then create nested defaults (applying inner defaults of that object).
 400
 401Note that if `value` is an object, any changes to the object after `default()` is called will change the reference
 402and any future assignment.
 403
 404Additionally, when specifying a method you must either have a `description` property on your method or the second parameter is required.
 405
 406```javascript
 407var generateUsername = function (context) {
 408
 409  return context.firstname.toLowerCase() + '-' + context.lastname.toLowerCase();
 410};
 411generateUsername.description = 'generated username';
 412
 413var schema = {
 414    username: Joi.string().default(generateUsername),
 415    firstname: Joi.string(),
 416    lastname: Joi.string(),
 417    created: Joi.date().default(Date.now, 'time of creation'),
 418    status: Joi.string().default('registered')
 419};
 420
 421Joi.validate({
 422    firstname: 'Jane',
 423    lastname: 'Doe'
 424}, schema, function (err, value) {
 425
 426    // value.status === 'registered'
 427    // value.username === 'jane-doe'
 428    // value.created will be the time of validation
 429});
 430```
 431
 432#### `any.concat(schema)`
 433
 434Returns a new type that is the result of adding the rules of one type to another where:
 435- `schema` - a **joi** type to merge into the current schema. Can only be of the same type as the context type or `any`. If applied to an `any` type, the schema can be any other schema.
 436
 437```javascript
 438var a = Joi.string().valid('a');
 439var b = Joi.string().valid('b');
 440var ab = a.concat(b);
 441```
 442
 443#### `any.when(ref, options)`
 444
 445Converts the type into an [`alternatives`](#alternatives) type where the conditions are merged into the type definition where:
 446- `ref` - the key name or [reference](#refkey-options).
 447- `options` - an object with:
 448    - `is` - the required condition **joi** type.
 449    - `then` - the alternative schema type if the condition is true. Required if `otherwise` is missing.
 450    - `otherwise` - the alternative schema type if the condition is false. Required if `then` is missing.
 451
 452```javascript
 453var schema = {
 454    a: Joi.any().valid('x').when('b', { is: 5, then: Joi.valid('y'), otherwise: Joi.valid('z') }),
 455    b: Joi.any()
 456};
 457```
 458
 459Alternatively, if you want to specify a specific type such as `string`, `array`, etc, you can do so like this:
 460
 461```javascript
 462var schema = {
 463    a: Joi.valid('a', 'b', 'other'),
 464    other: Joi.string()
 465        .when('a', { is: 'other', then: Joi.required() }),
 466};
 467```
 468
 469#### `any.label(name)`
 470
 471Overrides the key name in error messages.
 472- `name` - the name of the key.
 473
 474```javascript
 475var schema = {
 476    first_name: Joi.string().label('First Name')
 477};
 478```
 479
 480#### `any.raw(isRaw)`
 481
 482Outputs the original untouched value instead of the casted value.
 483- `isRaw` - whether to enable raw mode or not. Defaults to true.
 484
 485```javascript
 486var schema = {
 487    timestamp: Joi.date().format('YYYYMMDD').raw()
 488};
 489```
 490
 491#### `any.empty(schema)`
 492
 493Considers anything that matches the schema to be empty (`undefined`).
 494- `schema` - any object or joi schema to match. An undefined schema unsets that rule.
 495
 496```js
 497var schema = Joi.string().empty('');
 498schema.validate(''); // returns { error: null, value: undefined }
 499schema = schema.empty();
 500schema.validate(''); // returns { error: "value" is not allowed to be empty, value: '' }
 501```
 502
 503### `array`
 504
 505Generates a schema object that matches an array data type. Note that undefined values inside arrays are not allowed by default but can be by using `sparse()`.
 506
 507Supports the same methods of the [`any()`](#any) type.
 508
 509```javascript
 510var array = Joi.array().items(Joi.string().valid('a', 'b'));
 511array.validate(['a', 'b', 'a'], function (err, value) { });
 512```
 513
 514#### `array.sparse(enabled)`
 515
 516Allow this array to be sparse. `enabled` can be used with a falsy value to go back to the default behavior.
 517
 518```javascript
 519var schema = Joi.array().sparse(); // undefined values are now allowed
 520schema = schema.sparse(false); // undefined values are now denied
 521```
 522
 523#### `array.single(enabled)`
 524
 525Allow single values to be checked against rules as if it were provided as an array.
 526
 527`enabled` can be used with a falsy value to go back to the default behavior.
 528
 529```javascript
 530var schema = Joi.array().items(Joi.number()).single();
 531schema.validate([4]); // returns `{ error: null, value: [ 4 ] }`
 532schema.validate(4); // returns `{ error: null, value: [ 4 ] }`
 533```
 534
 535#### `array.items(type)`
 536
 537List the types allowed for the array values where:
 538- `type` - a **joi** schema object to validate each array item against. `type` can be an array of values, or multiple values can be passed as individual arguments.
 539
 540If a given type is `.required()` then there must be a matching item in the array.
 541If a type is `.forbidden()` then it cannot appear in the array.
 542Required items can be added multiple times to signify that multiple items must be found.
 543Errors will contain the number of items that didn't match. Any unmatched item having a [label](#anylabelname) will be mentioned explicitly.
 544
 545```javascript
 546var schema = Joi.array().items(Joi.string(), Joi.number()); // array may contain strings and numbers
 547var schema = Joi.array().items(Joi.string().required(), Joi.string().required()); // array must contain at least two strings
 548var schema = Joi.array().items(Joi.string().valid('not allowed').forbidden(), Joi.string()); // array may contain strings, but none of those strings can match 'not allowed'
 549var schema = Joi.array().items(Joi.string().label('My string').required(), Joi.number().required()); // If this fails it can result in `[ValidationError: "value" does not contain [My string] and 1 other required value(s)]`
 550```
 551
 552#### `array.ordered(type)`
 553
 554List the types in sequence order for the array values where:
 555- `type` - a **joi** schema object to validate against each array item in sequence order. `type` can be an array of values, or multiple values can be passed as individual arguments.
 556
 557If a given type is `.required()` then there must be a matching item with the same index position in the array.
 558Errors will contain the number of items that didn't match. Any unmatched item having a [label](#anylabelname) will be mentioned explicitly.
 559
 560```javascript
 561var schema = Joi.array().ordered(Joi.string().required(), Joi.number().required()); // array must have first item as string and second item as number
 562var schema = Joi.array().ordered(Joi.string().required()).items(Joi.number().required()); // array must have first item as string and 1 or more subsequent items as number
 563var schema = Joi.array().ordered(Joi.string().required(), Joi.number()); // array must have first item as string and optionally second item as number
 564```
 565
 566#### `array.min(limit)`
 567
 568Specifies the minimum number of items in the array where:
 569- `limit` - the lowest number of array items allowed.
 570
 571```javascript
 572var schema = Joi.array().min(2);
 573```
 574
 575#### `array.max(limit)`
 576
 577Specifies the maximum number of items in the array where:
 578- `limit` - the highest number of array items allowed.
 579
 580```javascript
 581var schema = Joi.array().max(10);
 582```
 583
 584#### `array.length(limit)`
 585
 586Specifies the exact number of items in the array where:
 587- `limit` - the number of array items allowed.
 588
 589```javascript
 590var schema = Joi.array().length(5);
 591```
 592
 593#### `array.unique()`
 594
 595Requires the array values to be unique.
 596
 597Be aware that a deep equality is performed on elements of the array having a type of `object`, a performance penalty is to be expected for this kind of operation.
 598
 599```javascript
 600var schema = Joi.array().unique();
 601```
 602
 603### `boolean`
 604
 605Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', 'no', 'on' or 'off'). Can also be called via `bool()`.
 606
 607Supports the same methods of the [`any()`](#any) type.
 608
 609```javascript
 610var boolean = Joi.boolean();
 611boolean.validate(true, function (err, value) { });
 612```
 613
 614### `binary`
 615
 616Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers).
 617
 618Supports the same methods of the [`any()`](#any) type.
 619
 620```javascript
 621var schema = Joi.binary();
 622```
 623
 624#### `binary.encoding(encoding)`
 625
 626Sets the string encoding format if a string input is converted to a buffer where:
 627- `encoding` - the encoding scheme.
 628
 629```javascript
 630var schema = Joi.binary().encoding('base64');
 631```
 632
 633#### `binary.min(limit)`
 634
 635Specifies the minimum length of the buffer where:
 636- `limit` - the lowest size of the buffer.
 637
 638```javascript
 639var schema = Joi.binary().min(2);
 640```
 641
 642#### `binary.max(limit)`
 643
 644Specifies the maximum length of the buffer where:
 645- `limit` - the highest size of the buffer.
 646
 647```javascript
 648var schema = Joi.binary().max(10);
 649```
 650
 651#### `binary.length(limit)`
 652
 653Specifies the exact length of the buffer:
 654- `limit` - the size of buffer allowed.
 655
 656```javascript
 657var schema = Joi.binary().length(5);
 658```
 659
 660### `date`
 661
 662Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds).
 663
 664Supports the same methods of the [`any()`](#any) type.
 665
 666```javascript
 667var date = Joi.date();
 668date.validate('12-21-2012', function (err, value) { });
 669```
 670
 671#### `date.min(date)`
 672
 673Specifies the oldest date allowed where:
 674- `date` - the oldest date allowed.
 675
 676```javascript
 677var schema = Joi.date().min('1-1-1974');
 678```
 679
 680Notes: `'now'` can be passed in lieu of `date` so as to always compare relatively to the current date, allowing to explicitly ensure a date is either in the past or in the future.
 681
 682```javascript
 683var schema = Joi.date().min('now');
 684```
 685
 686It can also be a reference to another field.
 687
 688```javascript
 689var schema = Joi.object({
 690  from: Joi.date().required(),
 691  to: Joi.date().min(Joi.ref('from')).required()
 692});
 693```
 694
 695#### `date.max(date)`
 696
 697Specifies the latest date allowed where:
 698- `date` - the latest date allowed.
 699
 700```javascript
 701var schema = Joi.date().max('12-31-2020');
 702```
 703
 704Notes: `'now'` can be passed in lieu of `date` so as to always compare relatively to the current date, allowing to explicitly ensure a date is either in the past or in the future.
 705
 706```javascript
 707var schema = Joi.date().max('now');
 708```
 709
 710It can also be a reference to another field.
 711
 712```javascript
 713var schema = Joi.object({
 714  from: Joi.date().max(Joi.ref('to')).required(),
 715  to: Joi.date().required()
 716});
 717```
 718
 719#### `date.format(format)`
 720
 721Specifies the allowed date format:
 722- `format` - string or array of strings that follow the `moment.js` [format](http://momentjs.com/docs/#/parsing/string-format/).
 723
 724```javascript
 725var schema = Joi.date().format('YYYY/MM/DD');
 726```
 727
 728#### `date.iso()`
 729
 730Requires the string value to be in valid ISO 8601 date format.
 731
 732```javascript
 733var schema = Joi.date().iso();
 734```
 735
 736### `func`
 737
 738Generates a schema object that matches a function type.
 739
 740Supports the same methods of the [`object()`](#object) type. Note that validating a function keys will cause the function
 741to be cloned. While the function will retain its prototype and closure, it will lose its `length` property value (will be
 742set to `0`).
 743
 744```javascript
 745var func = Joi.func();
 746func.validate(function () {}, function (err, value) { });
 747```
 748
 749### `number`
 750
 751Generates a schema object that matches a number data type (as well as strings that can be converted to numbers).
 752
 753`Infinity` and `-Infinity` are invalid by default, you can change that behavior by calling `allow(Infinity, -Infinity)`.
 754
 755Supports the same methods of the [`any()`](#any) type.
 756
 757```javascript
 758var number = Joi.number();
 759number.validate(5, function (err, value) { });
 760```
 761
 762#### `number.min(limit)`
 763
 764Specifies the minimum value where:
 765- `limit` - the minimum value allowed.
 766
 767```javascript
 768var schema = Joi.number().min(2);
 769```
 770
 771It can also be a reference to another field.
 772
 773```javascript
 774var schema = Joi.object({
 775  min: Joi.number().required(),
 776  max: Joi.number().min(Joi.ref('min')).required()
 777});
 778```
 779
 780#### `number.max(limit)`
 781
 782Specifies the maximum value where:
 783- `limit` - the maximum value allowed.
 784
 785```javascript
 786var schema = Joi.number().max(10);
 787```
 788
 789It can also be a reference to another field.
 790
 791```javascript
 792var schema = Joi.object({
 793  min: Joi.number().max(Joi.ref('max')).required(),
 794  max: Joi.number().required()
 795});
 796```
 797
 798#### `number.greater(limit)`
 799
 800Specifies that the value must be greater than `limit`.
 801
 802```javascript
 803var schema = Joi.number().greater(5);
 804```
 805
 806```javascript
 807var schema = Joi.object({
 808  min: Joi.number().required(),
 809  max: Joi.number().greater(Joi.ref('min')).required()
 810});
 811```
 812
 813#### `number.less(limit)`
 814
 815Specifies that the value must be less than `limit`.
 816
 817```javascript
 818var schema = Joi.number().less(10);
 819```
 820
 821It can also be a reference to another field.
 822
 823```javascript
 824var schema = Joi.object({
 825  min: Joi.number().less(Joi.ref('max')).required(),
 826  max: Joi.number().required()
 827});
 828```
 829
 830#### `number.integer()`
 831
 832Requires the number to be an integer (no floating point).
 833
 834```javascript
 835var schema = Joi.number().integer();
 836```
 837
 838#### `number.precision(limit)`
 839
 840Specifies the maximum number of decimal places where:
 841- `limit` - the maximum number of decimal places allowed.
 842
 843```javascript
 844var schema = Joi.number().precision(2);
 845```
 846
 847#### `number.multiple(base)`
 848
 849Specifies that the value must be a multiple of `base`:
 850
 851```javascript
 852var schema = Joi.number().multiple(3);
 853```
 854
 855#### `number.positive()`
 856
 857Requires the number to be positive.
 858
 859```javascript
 860var schema = Joi.number().positive();
 861```
 862
 863#### `number.negative()`
 864
 865Requires the number to be negative.
 866
 867```javascript
 868var schema = Joi.number().negative();
 869```
 870
 871### `object`
 872
 873Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects). Defaults
 874to allowing any child key.
 875
 876Supports the same methods of the [`any()`](#any) type.
 877
 878```javascript
 879var object = Joi.object().keys({
 880    a: Joi.number().min(1).max(10).integer(),
 881    b: 'some string'
 882});
 883
 884object.validate({ a: 5 }, function (err, value) { });
 885```
 886
 887#### `object.keys([schema])`
 888
 889Sets or extends the allowed object keys where:
 890- `schema` - optional object where each key is assigned a **joi** type object. If `schema` is `{}` no keys allowed.
 891  If `schema` is `null` or `undefined`, any key allowed. If `schema` is an object with keys, the keys are added to any
 892  previously defined keys (but narrows the selection if all keys previously allowed). Defaults to 'undefined' which
 893  allows any child key.
 894
 895```javascript
 896var base = Joi.object().keys({
 897    a: Joi.number(),
 898    b: Joi.string()
 899});
 900// Validate keys a, b and c.
 901var extended = base.keys({
 902    c: Joi.boolean()
 903});
 904```
 905
 906Notes: We have three different ways to define a schema for performing a validation
 907
 908- Using the plain JS object notation:
 909```javascript
 910var schema = {
 911    a: Joi.string(),
 912    b: Joi.number()
 913};
 914```
 915- Using the `Joi.object([schema])` notation
 916```javascript
 917var schema = Joi.object({
 918    a: Joi.string(),
 919    b: Joi.number()
 920});
 921```
 922- Using the `Joi.object().keys([schema])` notation
 923```javascript
 924var schema = Joi.object().keys({
 925    a: Joi.string(),
 926    b: Joi.number()
 927});
 928```
 929
 930While all these three objects defined above will result in the same validation object, there are some differences in using one or another:
 931
 932##### `{} notation`
 933
 934When using the `{}` notation, you are just defining a plain JS object, which isn't a schema object.
 935You can pass it to the validation method but you can't call `validate()` method of the object because it's just a plain JS object.
 936
 937Besides, passing the `{}` object to the `validate()` method each time, will perform an expensive schema compilation operation on every validation.
 938
 939##### `Joi.object([schema]) notation`
 940
 941Using `Joi.object([schema])` will return a schema object, so you can call the `validate()` method directly, e.g:
 942
 943```javascript
 944var schema = Joi.object({
 945    a: Joi.boolean()
 946});
 947
 948schema.validate(true, function (err, value) {
 949    console.log('err: ', err);
 950});
 951```
 952
 953When you use `Joi.object([schema])`, it gets compiled the first time, so you can pass it to the `validate()` method multiple times and no overhead is added.
 954
 955Another benefits of using `Joi.object([schema])` instead of a plain JS object is that you can set any options on the object like allowing unknown keys, e.g:
 956
 957```javascript
 958var schema = Joi.object({
 959    arg: Joi.string().valid('firstname', 'lastname', 'title', 'company', 'jobtitle'),
 960    value: Joi.string(),
 961}).pattern(/firstname|lastname/, Joi.string().min(2));
 962```
 963
 964##### `Joi.object().keys([schema]) notation`
 965
 966This is basically the same as `Joi.object([schema])`, but using `Joi.object().keys([schema])` is more useful when you want to add more keys (e.g. call `keys()` multiple times). If you are only adding one set of keys, you can skip the `keys()` method and just use `object()` directly.
 967
 968Some people like to use `keys()` to make the code more explicit (this is style only).
 969
 970
 971#### `object.min(limit)`
 972
 973Specifies the minimum number of keys in the object where:
 974- `limit` - the lowest number of keys allowed.
 975
 976```javascript
 977var schema = Joi.object().min(2);
 978```
 979
 980#### `object.max(limit)`
 981
 982Specifies the maximum number of keys in the object where:
 983- `limit` - the highest number of object keys allowed.
 984
 985```javascript
 986var schema = Joi.object().max(10);
 987```
 988
 989#### `object.length(limit)`
 990
 991Specifies the exact number of keys in the object where:
 992- `limit` - the number of object keys allowed.
 993
 994```javascript
 995var schema = Joi.object().length(5);
 996```
 997
 998#### `object.pattern(regex, schema)`
 999
1000Specify validation rules for unknown keys matching a pattern where:
1001- `regex` - a regular expression tested against the unknown key names.
1002- `schema` - the schema object matching keys much validate against.
1003
1004```javascrip
1005var schema = Joi.object({
1006    a: Joi.string()
1007}).pattern(/\w\d/, Joi.boolean());
1008```
1009
1010#### `object.and(peers)`
1011
1012Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as
1013well where:
1014- `peers` - the key names of which if one present, all are required. `peers` can be a single string value, an
1015  array of string values, or each peer provided as an argument.
1016
1017```javascript
1018var schema = Joi.object().keys({
1019    a: Joi.any(),
1020    b: Joi.any()
1021}).and('a', 'b');
1022```
1023
1024#### `object.nand(peers)`
1025
1026Defines a relationship between keys where not all peers can be present at the
1027same time where:
1028- `peers` - the key names of which if one present, the others may not all be present. `peers` can be a single string value, an
1029  array of string values, or each peer provided as an argument.
1030
1031```javascript
1032var schema = Joi.object().keys({
1033    a: Joi.any(),
1034    b: Joi.any()
1035}).nand('a', 'b');
1036```
1037
1038#### `object.or(peers)`
1039
1040Defines a relationship between keys where one of the peers is required (and more than one is allowed) where:
1041- `peers` - the key names of which at least one must appear. `peers` can be a single string value, an
1042  array of string values, or each peer provided as an argument.
1043
1044```javascript
1045var schema = Joi.object().keys({
1046    a: Joi.any(),
1047    b: Joi.any()
1048}).or('a', 'b');
1049```
1050
1051#### `object.xor(peers)`
1052
1053Defines an exclusive relationship between a set of keys where one of them is required but not at the same time where:
1054- `peers` - the exclusive key names that must not appear together but where one of them is required. `peers` can be a single string value, an
1055  array of string values, or each peer provided as an argument.
1056
1057```javascript
1058var schema = Joi.object().keys({
1059    a: Joi.any(),
1060    b: Joi.any()
1061}).xor('a', 'b');
1062```
1063
1064#### `object.with(key, peers)`
1065
1066Requires the presence of other keys whenever the specified key is present where:
1067- `key` - the reference key.
1068- `peers` - the required peer key names that must appear together with `key`. `peers` can be a single string value or an array of string values.
1069
1070Note that unlike [`object.and()`](#objectandpeers), `with()` creates a dependency only between the `key` and each of the `peers`, not
1071between the `peers` themselves.
1072
1073```javascript
1074var schema = Joi.object().keys({
1075    a: Joi.any(),
1076    b: Joi.any()
1077}).with('a', 'b');
1078```
1079
1080#### `object.without(key, peers)`
1081
1082Forbids the presence of other keys whenever the specified is present where:
1083- `key` - the reference key.
1084- `peers` - the forbidden peer key names that must not appear together with `key`. `peers` can be a single string value or an array of string values.
1085
1086```javascript
1087var schema = Joi.object().keys({
1088    a: Joi.any(),
1089    b: Joi.any()
1090}).without('a', ['b']);
1091```
1092
1093#### `object.rename(from, to, [options])`
1094
1095Renames a key to another name (deletes the renamed key) where:
1096- `from` - the original key name.
1097- `to` - the new key name.
1098- `options` - an optional object with the following optional keys:
1099    - `alias` - if `true`, does not delete the old key name, keeping both the new and old keys in place. Defaults to `false`.
1100    - `multiple` - if `true`, allows renaming multiple keys to the same destination where the last rename wins. Defaults to `false`.
1101    - `override` - if `true`, allows renaming a key over an existing key. Defaults to `false`.
1102    - `ignoreUndefined` - if `true`, skip renaming of a key if it's undefined. Defaults to `false`.
1103
1104Keys are renamed before any other validation rules are applied.
1105
1106```javascript
1107var object = Joi.object().keys({
1108    a: Joi.number()
1109}).rename('b', 'a');
1110
1111object.validate({ b: 5 }, function (err, value) { });
1112```
1113
1114#### `object.assert(ref, schema, [message])`
1115
1116Verifies an assertion where:
1117- `ref` - the key name or [reference](#refkey-options).
1118- `schema` - the validation rules required to satisfy the assertion. If the `schema` includes references, they are resolved against
1119  the object value, not the value of the `ref` target.
1120- `message` - optional human-readable message used when the assertion fails. Defaults to 'failed to pass the assertion test'.
1121
1122```javascript
1123var schema = Joi.object().keys({
1124    a: {
1125        b: Joi.string(),
1126        c: Joi.number()
1127    },
1128    d: {
1129        e: Joi.any()
1130    }
1131}).assert('d.e', Joi.ref('a.c'), 'equal to a.c');
1132```
1133
1134#### `object.unknown([allow])`
1135
1136Overrides the handling of unknown keys for the scope of the current object only (does not apply to children) where:
1137- `allow` - if `false`, unknown keys are not allowed, otherwise unknown keys are ignored.
1138
1139```javascript
1140var schema = Joi.object({ a: Joi.any() }).unknown();
1141```
1142
1143#### `object.type(constructor, [name])`
1144
1145Requires the object to be an instance of a given constructor where:
1146- `constructor` - the constructor function that the object must be an instance of.
1147- `name` - an alternate name to use in validation errors. This is useful when the constructor function does not have a name.
1148
1149```javascript
1150var schema = Joi.object().type(RegExp);
1151```
1152
1153#### `object.requiredKeys(children)`
1154
1155Sets the specified children to required.
1156- `children` - can be a single string value, an array of string values, or each child provided as an argument.
1157
1158```javascript
1159var schema = Joi.object().keys({ a: { b: Joi.number() }, c: { d: Joi.string() } });
1160var requiredSchema = schema.requiredKeys('', 'a.b', 'c', 'c.d');
1161```
1162
1163Note that in this example `''` means the current object, `a` is not required but `b` is, as well as `c` and `d`.
1164
1165#### `object.optionalKeys(children)`
1166
1167Sets the specified children to optional.
1168- `children` - can be a single string value, an array of string values, or each child provided as an argument.
1169
1170```javascript
1171var schema = Joi.object().keys({ a: { b: Joi.number().required() }, c: { d: Joi.string().required() } });
1172var requiredSchema = schema.optionalKeys('a.b', 'c.d');
1173```
1174
1175The behavior is exactly the same as `requiredKeys`.
1176
1177### `string`
1178
1179Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with `allow('')`.
1180
1181Supports the same methods of the [`any()`](#any) type.
1182
1183```javascript
1184var schema = Joi.string().min(1).max(10);
1185schema.validate('12345', function (err, value) { });
1186```
1187
1188#### `string.insensitive()`
1189
1190Allows the value to match any whitelist of blacklist item in a case insensitive comparison.
1191
1192```javascript
1193var schema = Joi.string().valid('a').insensitive();
1194```
1195
1196#### `string.min(limit, [encoding])`
1197
1198Specifies the minimum number string characters where:
1199- `limit` - the minimum number of string characters required.
1200- `encoding` - is specified, the string length is calculated in bytes using the provided encoding.
1201
1202```javascript
1203var schema = Joi.string().min(2);
1204```
1205
1206It can also be a reference to another field.
1207
1208```javascript
1209var schema = Joi.object({
1210  min: Joi.string().required(),
1211  value: Joi.string().min(Joi.ref('min'), 'utf8').required()
1212});
1213```
1214
1215#### `string.max(limit, [encoding])`
1216
1217Specifies the maximum number of string characters where:
1218- `limit` - the maximum number of string characters allowed.
1219- `encoding` - is specified, the string length is calculated in bytes using the provided encoding.
1220
1221```javascript
1222var schema = Joi.string().max(10);
1223```
1224
1225It can also be a reference to another field.
1226
1227```javascript
1228var schema = Joi.object({
1229  max: Joi.string().required(),
1230  value: Joi.string().max(Joi.ref('max'), 'utf8').required()
1231});
1232```
1233
1234#### `string.creditCard()`
1235
1236Requires the number to be a credit card number (Using [Lunh
1237Algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm)).
1238
1239```javascript
1240var schema = Joi.string().creditCard();
1241```
1242
1243#### `string.length(limit, [encoding])`
1244
1245Specifies the exact string length required where:
1246- `limit` - the required string length.
1247- `encoding` - is specified, the string length is calculated in bytes using the provided encoding.
1248
1249```javascript
1250var schema = Joi.string().length(5);
1251```
1252
1253It can also be a reference to another field.
1254
1255```javascript
1256var schema = Joi.object({
1257  length: Joi.string().required(),
1258  value: Joi.string().length(Joi.ref('length'), 'utf8').required()
1259});
1260```
1261
1262#### `string.regex(pattern, [name])`
1263
1264Defines a regular expression rule where:
1265- `pattern` - a regular expression object the string value must match against.
1266- `name` - optional name for patterns (useful with multiple patterns). Defaults to 'required'.
1267
1268```javascript
1269var schema = Joi.string().regex(/^[abc]+$/);
1270```
1271
1272#### `string.replace(pattern, replacement)`
1273
1274Replace characters matching the given _pattern_ with the specified
1275_replacement_ string where:
1276- `pattern` - a regular expression object to match against, or a string of which _all_ occurrences will be replaced.
1277- `replacement` - the string that will replace the pattern.
1278
1279
1280```javascript
1281var schema = Joi.string().replace(/b/gi, 'x');
1282schema.validate('abBc', function (err, value) {
1283  // here value will be 'axxc'
1284});
1285```
1286
1287When `pattern` is a _string_ all its occurrences will be replaced.
1288
1289#### `string.alphanum()`
1290
1291Requires the string value to only contain a-z, A-Z, and 0-9.
1292
1293```javascript
1294var schema = Joi.string().alphanum();
1295```
1296
1297#### `string.token()`
1298
1299Requires the string value to only contain a-z, A-Z, 0-9, and underscore _.
1300
1301```javascript
1302var schema = Joi.string().token();
1303```
1304
1305#### `string.email([options])`
1306
1307Requires the string value to be a valid email address.
1308
1309- `options` - optional settings:
1310    - `errorLevel` - Numerical threshold at which an email address is considered invalid.
1311    - `tldWhitelist` - Specifies a list of acceptable TLDs.
1312    - `minDomainAtoms` - Number of atoms required for the domain. Be careful since some domains, such as `io`, directly allow email.
1313
1314```javascript
1315var schema = Joi.string().email();
1316```
1317
1318#### `string.ip([options])`
1319
1320Requires the string value to be a valid ip address.
1321
1322- `options` - optional settings:
1323    - `version` - One or more IP address versions to validate against. Valid values: `ipv4`, `ipv6`, `ipvfuture`
1324    - `cidr` - Used to determine if a CIDR is allowed or not. Valid values: `optional`, `required`, `forbidden`
1325
1326```javascript
1327// Accept only ipv4 and ipv6 addresses with a CIDR
1328var schema = Joi.string().ip({
1329  version: [
1330    'ipv4',
1331    'ipv6'
1332  ],
1333  cidr: 'required'
1334});
1335```
1336
1337#### `string.uri([options])`
1338
1339Requires the string value to be a valid [RFC 3986](http://tools.ietf.org/html/rfc3986) URI.
1340
1341- `options` - optional settings:
1342    - `scheme` - Specifies one or more acceptable Schemes, should only include the scheme name. Can be an Array or String (strings are automatically escaped for use in a Regular Expression).
1343
1344```javascript
1345// Accept git or git http/https
1346var schema = Joi.string().uri({
1347  scheme: [
1348    'git',
1349    /git\+https?/
1350  ]
1351});
1352```
1353
1354#### `string.guid()`
1355
1356Requires the string value to be a valid GUID.
1357
1358```javascript
1359var schema = Joi.string().guid();
1360```
1361
1362#### `string.hex()`
1363
1364Requires the string value to be a valid hexadecimal string.
1365
1366```javascript
1367var schema = Joi.string().hex();
1368```
1369
1370#### `string.hostname()`
1371
1372Requires the string value to be a valid hostname as per [RFC1123](http://tools.ietf.org/html/rfc1123).
1373
1374```javascript
1375var schema = Joi.string().hostname();
1376```
1377
1378#### `string.lowercase()`
1379
1380Requires the string value to be all lowercase. If the validation `convert` option is on (enabled by default), the string
1381will be forced to lowercase.
1382
1383```javascript
1384var schema = Joi.string().lowercase();
1385```
1386
1387#### `string.uppercase()`
1388
1389Requires the string value to be all uppercase. If the validation `convert` option is on (enabled by default), the string
1390will be forced to uppercase.
1391
1392```javascript
1393var schema = Joi.string().uppercase();
1394```
1395
1396#### `string.trim()`
1397
1398Requires the string value to contain no whitespace before or after. If the validation `convert` option is on (enabled by
1399default), the string will be trimmed.
1400
1401```javascript
1402var schema = Joi.string().trim();
1403```
1404
1405#### `string.isoDate()`
1406
1407Requires the string value to be in valid ISO 8601 date format.
1408
1409```js
1410var schema = Joi.string().isoDate();
1411```
1412
1413### `alternatives`
1414
1415Generates a type that will match one of the provided alternative schemas via the [`try()`](#alternativestryschemas)
1416method. If no schemas are added, the type will not match any value except for `undefined`.
1417
1418Supports the same methods of the [`any()`](#any) type.
1419
1420Alternatives can be expressed using the shorter `[]` notation.
1421
1422```javascript
1423var alt = Joi.alternatives().try(Joi.number(), Joi.string());
1424// Same as [Joi.number(), Joi.string()]
1425```
1426
1427#### `alternatives.try(schemas)`
1428
1429Adds an alternative schema type for attempting to match against the validated value where:
1430- `schema` - an array of alternative **joi** types. Also supports providing each type as a separate argument.
1431
1432```javascript
1433var alt = Joi.alternatives().try(Joi.number(), Joi.string());
1434alt.validate('a', function (err, value) { });
1435```
1436
1437#### `alternatives.when(ref, options)`
1438
1439Adds a conditional alternative schema type based on another key (not the same as `any.when()`) value where:
1440- `ref` - the key name or [reference](#refkey-options).
1441- `options` - an object with:
1442    - `is` - the required condition **joi** type.
1443    - `then` - the alternative schema type to **try** if the condition is true. Required if `otherwise` is missing.
1444    - `otherwise` - the alternative schema type to **try** if the condition is false. Required if `then` is missing.
1445
1446```javascript
1447var schema = {
1448    a: Joi.alternatives().when('b', { is: 5, then: Joi.string(), otherwise: Joi.number() }),
1449    b: Joi.any()
1450};
1451```
1452
1453Note that `when()` only adds additional alternatives to try and does not impact the overall type. Setting
1454a `required()` rule on a single alternative will not apply to the overall key. For example,
1455this definition of `a`:
1456
1457```javascript
1458var schema = {
1459    a: Joi.alternatives().when('b', { is: true, then: Joi.required() }),
1460    b: Joi.boolean()
1461};
1462```
1463
1464Does not turn `a` into a required key when `b` is `true`. Instead, it tells the validator to try and match the
1465value to anything that's not `undefined`. However, since `Joi.alternatives()` by itself allows `undefined`, the rule
1466does not accomplish turning `a` to a required value. This rule is the same as `Joi.alternatives([Joi.required()])`
1467when `b` is `true` which will allow any value including `undefined`.
1468
1469To accomplish the desired result above use:
1470
1471```javascript
1472var schema = {
1473    a: Joi.when('b', { is: true, then: Joi.required() }),
1474    b: Joi.boolean()
1475};
1476```
1477
1478### `ref(key, [options])`
1479
1480Generates a reference to the value of the named key. References are resolved at validation time and in order of dependency
1481so that if one key validation depends on another, the dependent key is validated second after the reference is validated.
1482References support the following arguments:
1483- `key` - the reference target. References cannot point up the object tree, only to sibling keys, but they can point to
1484  their siblings' children (e.g. 'a.b.c') using the `.` separator. If a `key` starts with `$` is signifies a context reference
1485  which is looked up in the `context` option object.
1486- `options` - optional settings:
1487    - `separator` - overrides the default `.` hierarchy separator.
1488    - `contextPrefix` - overrides the default `$` context prefix signifier.
1489
1490Note that references can only be used where explicitly supported such as in `valid()` or `invalid()` rules. If upwards
1491(parents) references are needed, use [`object.assert()`](#objectassertref-schema-message).
1492
1493```javascript
1494var schema = Joi.object().keys({
1495    a: Joi.ref('b.c'),
1496    b: {
1497        c: Joi.any()
1498    },
1499    c: Joi.ref('$x')
1500});
1501
1502Joi.validate({ a: 5, b: { c: 5 } }, schema, { context: { x: 5 } }, function (err, value) {});
1503```
1504
1505## Errors
1506
1507Joi throws classical javascript `Error`s containing :
1508- `name` - `ValidationError`.
1509- `details` - an array of errors :
1510    - `message` - string with a description of the error.
1511    - `path` - dotted path to the key where the error happened.
1512    - `type` - type of the error.
1513    - `context` - object providing context of the error.
1514- `annotate` - function that returns a string with an annotated version of the object pointing at the places where errors occured.
1515- `_object` - the original object to validate.