UNPKG

79.1 kBTypeScriptView Raw
1// Type definitions for @hapi/joi 17.1
2// Project: https://github.com/hapijs/joi
3// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
4// Laurence Dougal Myers <https://github.com/laurence-myers>
5// Christopher Glantschnig <https://github.com/cglantschnig>
6// David Broder-Rodgers <https://github.com/DavidBR-SW>
7// Gael Magnan de Bornier <https://github.com/GaelMagnan>
8// Rytis Alekna <https://github.com/ralekna>
9// Pavel Ivanov <https://github.com/schfkt>
10// Youngrok Kim <https://github.com/rokoroku>
11// Dan Kraus <https://github.com/dankraus>
12// Anjun Wang <https://github.com/wanganjun>
13// Rafael Kallis <https://github.com/rafaelkallis>
14// Conan Lai <https://github.com/aconanlai>
15// Peter Thorson <https://github.com/zaphoyd>
16// Will Garcia <https://github.com/thewillg>
17// Simon Schick <https://github.com/SimonSchick>
18// Alejandro Fernandez Haro <https://github.com/afharo>
19// Silas Rech <https://github.com/lenovouser>
20// Anand Chowdhary <https://github.com/AnandChowdhary>
21// Miro Yovchev <https://github.com/myovchev>
22// David Recuenco <https://github.com/RecuencoJones>
23// Frederic Reisenhauer <https://github.com/freisenhauer>
24// Stefan-Gabriel Muscalu <https://github.com/legraphista>
25// Simcha Wood <https://github.com/SimchaWood>
26// Steven Barnett <https://github.com/stevendesu>
27// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
28// TypeScript Version: 2.8
29
30// TODO express type of Schema in a type-parameter (.default, .valid, .example etc)
31
32declare namespace Joi {
33 type Types =
34 | 'any'
35 | 'alternatives'
36 | 'array'
37 | 'boolean'
38 | 'binary'
39 | 'date'
40 | 'function'
41 | 'link'
42 | 'number'
43 | 'object'
44 | 'string'
45 | 'symbol';
46
47 type BasicType = boolean|number|string|any[]|object|null;
48
49 type LanguageMessages = Record<string, string>;
50
51 type PresenceMode = 'optional' | 'required' | 'forbidden';
52
53 interface ErrorFormattingOptions {
54 /**
55 * when true, error message templates will escape special characters to HTML entities, for security purposes.
56 *
57 * @default false
58 */
59 escapeHtml?: boolean | undefined;
60 /**
61 * defines the value used to set the label context variable.
62 */
63 label?: 'path' | 'key' | false | undefined;
64 /**
65 * The preferred language code for error messages.
66 * The value is matched against keys at the root of the messages object, and then the error code as a child key of that.
67 * Can be a reference to the value, global context, or local context which is the root value passed to the validation function.
68 *
69 * Note that references to the value are usually not what you want as they move around the value structure relative to where the error happens.
70 * Instead, either use the global context, or the absolute value (e.g. `Joi.ref('/variable')`)
71 */
72 language?: keyof LanguageMessages | undefined;
73 /**
74 * when false, skips rendering error templates. Useful when error messages are generated elsewhere to save processing time.
75 *
76 * @default true
77 */
78 render?: boolean | undefined;
79 /**
80 * when true, the main error will possess a stack trace, otherwise it will be disabled.
81 * Defaults to false for performances reasons. Has no effect on platforms other than V8/node.js as it uses the Stack trace API.
82 *
83 * @default false
84 */
85 stack?: boolean | undefined;
86 /**
87 * overrides the way values are wrapped (e.g. `[]` arround arrays, `""` around labels).
88 * Each key can be set to a string with one (same character before and after the value) or two characters (first character
89 * before and second character after), or `false` to disable wrapping.
90 */
91 wrap?: {
92 /**
93 * the characters used around `{#label}` references. Defaults to `'"'`.
94 *
95 * @default '"'
96 */
97 label?: string|false | undefined,
98
99 /**
100 * the characters used around array avlues. Defaults to `'[]'`
101 *
102 * @default '[]'
103 */
104 array?: string|false | undefined
105 } | undefined;
106 }
107
108 interface BaseValidationOptions {
109 /**
110 * when true, stops validation on the first error, otherwise returns all the errors found.
111 *
112 * @default true
113 */
114 abortEarly?: boolean | undefined;
115 /**
116 * when true, allows object to contain unknown keys which are ignored.
117 *
118 * @default false
119 */
120 allowUnknown?: boolean | undefined;
121 /**
122 * when true, schema caching is enabled (for schemas with explicit caching rules).
123 *
124 * @default false
125 */
126 cache?: boolean | undefined;
127 /**
128 * provides an external data set to be used in references
129 */
130 context?: Context | undefined;
131 /**
132 * when true, attempts to cast values to the required types (e.g. a string to a number).
133 *
134 * @default true
135 */
136 convert?: boolean | undefined;
137 /**
138 * sets the string format used when converting dates to strings in error messages and casting.
139 *
140 * @default 'iso'
141 */
142 dateFormat?: 'date' | 'iso' | 'string' | 'time' | 'utc' | undefined;
143 /**
144 * when true, valid results and throw errors are decorated with a debug property which includes an array of the validation steps used to generate the returned result.
145 *
146 * @default false
147 */
148 debug?: boolean | undefined;
149 /**
150 * error formatting settings.
151 */
152 errors?: ErrorFormattingOptions | undefined;
153 /**
154 * if false, the external rules set with `any.external()` are ignored, which is required to ignore any external validations in synchronous mode (or an exception is thrown).
155 *
156 * @default true
157 */
158 externals?: boolean | undefined;
159 /**
160 * when true, do not apply default values.
161 *
162 * @default false
163 */
164 noDefaults?: boolean | undefined;
165 /**
166 * when true, inputs are shallow cloned to include non-enumerables properties.
167 *
168 * @default false
169 */
170 nonEnumerables?: boolean | undefined;
171 /**
172 * sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'.
173 *
174 * @default 'optional'
175 */
176 presence?: PresenceMode | undefined;
177 /**
178 * when true, ignores unknown keys with a function value.
179 *
180 * @default false
181 */
182 skipFunctions?: boolean | undefined;
183 /**
184 * remove unknown elements from objects and arrays.
185 * - when true, all unknown elements will be removed
186 * - when an object:
187 * - objects - set to true to remove unknown keys from objects
188 *
189 * @default false
190 */
191 stripUnknown?: boolean | { arrays?: boolean | undefined; objects?: boolean | undefined } | undefined;
192 }
193
194 interface ValidationOptions extends BaseValidationOptions {
195 /**
196 * overrides individual error messages. Defaults to no override (`{}`).
197 * Messages use the same rules as templates.
198 * Variables in double braces `{{var}}` are HTML escaped if the option `errors.escapeHtml` is set to true.
199 *
200 * @default {}
201 */
202 messages?: LanguageMessages | undefined;
203 }
204
205 interface AsyncValidationOptions extends ValidationOptions {
206 /**
207 * when true, warnings are returned alongside the value (i.e. `{ value, warning }`).
208 *
209 * @default false
210 */
211 warnings?: boolean | undefined;
212 }
213
214 interface LanguageMessageTemplate {
215 source: string;
216 rendered: string;
217 }
218
219 interface ErrorValidationOptions extends BaseValidationOptions {
220 messages?: Record<string, LanguageMessageTemplate> | undefined;
221 }
222
223 interface RenameOptions {
224 /**
225 * if true, does not delete the old key name, keeping both the new and old keys in place.
226 *
227 * @default false
228 */
229 alias?: boolean | undefined;
230 /**
231 * if true, allows renaming multiple keys to the same destination where the last rename wins.
232 *
233 * @default false
234 */
235 multiple?: boolean | undefined;
236 /**
237 * if true, allows renaming a key over an existing key.
238 *
239 * @default false
240 */
241 override?: boolean | undefined;
242 /**
243 * if true, skip renaming of a key if it's undefined.
244 *
245 * @default false
246 */
247 ignoreUndefined?: boolean | undefined;
248 }
249
250 interface TopLevelDomainOptions {
251 /**
252 * - `true` to use the IANA list of registered TLDs. This is the default value.
253 * - `false` to allow any TLD not listed in the `deny` list, if present.
254 * - A `Set` or array of the allowed TLDs. Cannot be used together with `deny`.
255 */
256 allow?: Set<string> | string[] | boolean | undefined;
257 /**
258 * - A `Set` or array of the forbidden TLDs. Cannot be used together with a custom `allow` list.
259 */
260 deny?: Set<string> | string[] | undefined;
261 }
262
263 interface HierarchySeparatorOptions {
264 /**
265 * overrides the default `.` hierarchy separator. Set to false to treat the key as a literal value.
266 *
267 * @default '.'
268 */
269 separator?: string | false | undefined;
270 }
271
272 interface EmailOptions {
273 /**
274 * If `true`, Unicode characters are permitted
275 *
276 * @default true
277 */
278 allowUnicode?: boolean | undefined;
279 /**
280 * if `true`, ignore invalid email length errors.
281 *
282 * @default false
283 */
284 ignoreLength?: boolean | undefined;
285 /**
286 * if true, allows multiple email addresses in a single string, separated by , or the separator characters.
287 *
288 * @default false
289 */
290 multiple?: boolean | undefined;
291 /**
292 * when multiple is true, overrides the default , separator. String can be a single character or multiple separator characters.
293 *
294 * @default ','
295 */
296 separator?: string | string[] | undefined;
297 /**
298 * Options for TLD (top level domain) validation. By default, the TLD must be a valid name listed on the [IANA registry](http://data.iana.org/TLD/tlds-alpha-by-domain.txt)
299 *
300 * @default { allow: true }
301 */
302 tlds?: TopLevelDomainOptions | false | undefined;
303 /**
304 * Number of segments required for the domain. Be careful since some domains, such as `io`, directly allow email.
305 *
306 * @default 2
307 */
308 minDomainSegments?: number | undefined;
309 }
310
311 interface DomainOptions {
312 /**
313 * If `true`, Unicode characters are permitted
314 *
315 * @default true
316 */
317 allowUnicode?: boolean | undefined;
318
319 /**
320 * Options for TLD (top level domain) validation. By default, the TLD must be a valid name listed on the [IANA registry](http://data.iana.org/TLD/tlds-alpha-by-domain.txt)
321 *
322 * @default { allow: true }
323 */
324 tlds?: TopLevelDomainOptions | false | undefined;
325 /**
326 * Number of segments required for the domain.
327 *
328 * @default 2
329 */
330 minDomainSegments?: number | undefined;
331 }
332
333 interface HexOptions {
334 /**
335 * hex decoded representation must be byte aligned.
336 * @default false
337 */
338 byteAligned?: boolean | undefined;
339 }
340
341 interface IpOptions {
342 /**
343 * One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture
344 */
345 version?: string | string[] | undefined;
346 /**
347 * Used to determine if a CIDR is allowed or not. Valid values: optional, required, forbidden
348 */
349 cidr?: PresenceMode | undefined;
350 }
351
352 type GuidVersions = 'uuidv1' | 'uuidv2' | 'uuidv3' | 'uuidv4' | 'uuidv5';
353
354 interface GuidOptions {
355 version: GuidVersions[] | GuidVersions;
356 }
357
358 interface UriOptions {
359 /**
360 * Specifies one or more acceptable Schemes, should only include the scheme name.
361 * Can be an Array or String (strings are automatically escaped for use in a Regular Expression).
362 */
363 scheme?: string | RegExp | Array<string | RegExp> | undefined;
364 /**
365 * Allow relative URIs.
366 *
367 * @default false
368 */
369 allowRelative?: boolean | undefined;
370 /**
371 * Restrict only relative URIs.
372 *
373 * @default false
374 */
375 relativeOnly?: boolean | undefined;
376 /**
377 * Allows unencoded square brackets inside the query string.
378 * This is NOT RFC 3986 compliant but query strings like abc[]=123&abc[]=456 are very common these days.
379 *
380 * @default false
381 */
382 allowQuerySquareBrackets?: boolean | undefined;
383 /**
384 * Validate the domain component using the options specified in `string.domain()`.
385 */
386 domain?: DomainOptions | undefined;
387 }
388
389 interface DataUriOptions {
390 /**
391 * optional parameter defaulting to true which will require `=` padding if true or make padding optional if false
392 *
393 * @default true
394 */
395 paddingRequired?: boolean | undefined;
396 }
397
398 interface Base64Options extends Pick<DataUriOptions, 'paddingRequired'> {
399 /**
400 * if true, uses the URI-safe base64 format which replaces `+` with `-` and `\` with `_`.
401 *
402 * @default false
403 */
404 urlSafe?: boolean | undefined;
405 }
406
407 interface SwitchCases {
408 /**
409 * the required condition joi type.
410 */
411 is: SchemaLike;
412 /**
413 * the alternative schema type if the condition is true.
414 */
415 then: SchemaLike;
416 }
417
418 interface SwitchDefault {
419 /**
420 * the alternative schema type if no cases matched.
421 * Only one otherwise statement is allowed in switch as the last array item.
422 */
423 otherwise: SchemaLike;
424 }
425
426 interface WhenOptions {
427 /**
428 * the required condition joi type.
429 */
430 is?: SchemaLike | undefined;
431
432 /**
433 * the negative version of `is` (`then` and `otherwise` have reverse
434 * roles).
435 */
436 not?: SchemaLike | undefined;
437
438 /**
439 * the alternative schema type if the condition is true. Required if otherwise or switch are missing.
440 */
441 then?: SchemaLike | undefined;
442
443 /**
444 * the alternative schema type if the condition is false. Required if then or switch are missing.
445 */
446 otherwise?: SchemaLike | undefined;
447
448 /**
449 * the list of cases. Required if then is missing. Required if then or otherwise are missing.
450 */
451 switch?: Array<SwitchCases | SwitchDefault> | undefined;
452
453 /**
454 * whether to stop applying further conditions if the condition is true.
455 */
456 break?: boolean | undefined;
457 }
458
459 interface WhenSchemaOptions {
460 /**
461 * the alternative schema type if the condition is true. Required if otherwise is missing.
462 */
463 then?: SchemaLike | undefined;
464 /**
465 * the alternative schema type if the condition is false. Required if then is missing.
466 */
467 otherwise?: SchemaLike | undefined;
468 }
469
470 interface Cache {
471 /**
472 * Add an item to the cache.
473 *
474 * Note that key and value can be anything including objects, array, etc.
475 */
476 set(key: any, value: any): void;
477
478 /**
479 * Retrieve an item from the cache.
480 *
481 * Note that key and value can be anything including objects, array, etc.
482 */
483 get(key: any): any;
484 }
485 interface CacheProvisionOptions {
486 /**
487 * number of items to store in the cache before the least used items are dropped.
488 *
489 * @default 1000
490 */
491 max: number;
492 }
493
494 interface CacheConfiguration {
495 /**
496 * Provisions a simple LRU cache for caching simple inputs (`undefined`, `null`, strings, numbers, and booleans).
497 */
498 provision(options?: CacheProvisionOptions): void;
499 }
500
501 interface CompileOptions {
502 /**
503 * If true and the provided schema is (or contains parts) using an older version of joi, will return a compiled schema that is compatible with the older version.
504 * If false, the schema is always compiled using the current version and if older schema components are found, an error is thrown.
505 */
506 legacy: boolean;
507 }
508
509 interface IsSchemaOptions {
510 /**
511 * If true, will identify schemas from older versions of joi, otherwise will throw an error.
512 *
513 * @default false
514 */
515 legacy: boolean;
516 }
517
518 interface ReferenceOptions extends HierarchySeparatorOptions {
519 /**
520 * a function with the signature `function(value)` where `value` is the resolved reference value and the return value is the adjusted value to use.
521 * Note that the adjust feature will not perform any type validation on the adjusted value and it must match the value expected by the rule it is used in.
522 * Cannot be used with `map`.
523 *
524 * @example `(value) => value + 5`
525 */
526 adjust?: ((value: any) => any) | undefined;
527
528 /**
529 * an array of array pairs using the format `[[key, value], [key, value]]` used to maps the resolved reference value to another value.
530 * If the resolved value is not in the map, it is returned as-is.
531 * Cannot be used with `adjust`.
532 */
533 map?: Array<[any, any]> | undefined;
534
535 /**
536 * overrides default prefix characters.
537 */
538 prefix?: {
539 /**
540 * references to the globally provided context preference.
541 *
542 * @default '$'
543 */
544 global?: string | undefined;
545
546 /**
547 * references to error-specific or rule specific context.
548 *
549 * @default '#'
550 */
551 local?: string | undefined;
552
553 /**
554 * references to the root value being validated.
555 *
556 * @default '/'
557 */
558 root?: string | undefined;
559 } | undefined;
560
561 /**
562 * If set to a number, sets the reference relative starting point.
563 * Cannot be combined with separator prefix characters.
564 * Defaults to the reference key prefix (or 1 if none present)
565 */
566 ancestor?: number | undefined;
567
568 /**
569 * creates an in-reference.
570 */
571 in?: boolean | undefined;
572
573 /**
574 * when true, the reference resolves by reaching into maps and sets.
575 */
576 iterables?: boolean | undefined;
577 }
578
579 interface StringRegexOptions {
580 /**
581 * optional pattern name.
582 */
583 name?: string | undefined;
584
585 /**
586 * when true, the provided pattern will be disallowed instead of required.
587 *
588 * @default false
589 */
590 invert?: boolean | undefined;
591 }
592
593 interface RuleOptions {
594 /**
595 * if true, the rules will not be replaced by the same unique rule later.
596 *
597 * For example, `Joi.number().min(1).rule({ keep: true }).min(2)` will keep both `min()` rules instead of the later rule overriding the first.
598 *
599 * @default false
600 */
601 keep?: boolean | undefined;
602
603 /**
604 * a single message string or a messages object where each key is an error code and corresponding message string as value.
605 *
606 * The object is the same as the messages used as an option in `any.validate()`.
607 * The strings can be plain messages or a message template.
608 */
609 message?: string | LanguageMessages | undefined;
610
611 /**
612 * if true, turns any error generated by the ruleset to warnings.
613 */
614 warn?: boolean | undefined;
615 }
616
617 interface ErrorReport extends Error {
618 code: string;
619 flags: Record<string, ExtensionFlag>;
620 path: string[];
621 prefs: ErrorValidationOptions;
622 messages: LanguageMessages;
623 state: State;
624 value: any;
625 }
626
627 interface ValidationError extends Error {
628 name: 'ValidationError';
629
630 isJoi: boolean;
631
632 /**
633 * array of errors.
634 */
635 details: ValidationErrorItem[];
636
637 /**
638 * function that returns a string with an annotated version of the object pointing at the places where errors occurred.
639 *
640 * NOTE: This method does not exist in browser builds of Joi
641 *
642 * @param stripColors - if truthy, will strip the colors out of the output.
643 */
644 annotate(stripColors?: boolean): string;
645
646 _object: any;
647 }
648
649 interface ValidationErrorItem {
650 message: string;
651 path: Array<string | number>;
652 type: string;
653 context?: Context | undefined;
654 }
655
656 type ValidationErrorFunction = (errors: ErrorReport[]) => string | ValidationErrorItem | Error;
657
658 interface ValidationResult {
659 error?: ValidationError | undefined;
660 errors?: ValidationError | undefined;
661 warning?: ValidationError | undefined;
662 value: any;
663 }
664
665 interface CreateErrorOptions {
666 flags?: boolean | undefined;
667 messages?: LanguageMessages | undefined;
668 }
669
670 interface ModifyOptions {
671 each?: boolean | undefined;
672 once?: boolean | undefined;
673 ref?: boolean | undefined;
674 schema?: boolean | undefined;
675 }
676
677 interface MutateRegisterOptions {
678 family?: any;
679 key?: any;
680 }
681
682 interface SetFlagOptions {
683 clone: boolean;
684 }
685
686 interface CustomHelpers<V = any> {
687 schema: ExtensionBoundSchema;
688 state: State;
689 prefs: ValidationOptions;
690 original: V;
691 warn: (code: string, local?: Context) => void;
692 error: (code: string, local?: Context) => ErrorReport;
693 message: (messages: LanguageMessages, local?: Context) => ErrorReport;
694 }
695
696 type CustomValidator<V = any> = (value: V, helpers: CustomHelpers) => V;
697
698 type ExternalValidationFunction = (value: any) => any;
699
700 type SchemaLike = string | number | boolean | object | null | Schema | SchemaMap;
701
702 type SchemaMap<TSchema = any> = {
703 [key in keyof TSchema]?: SchemaLike | SchemaLike[];
704 };
705
706 type Schema =
707 | AnySchema
708 | ArraySchema
709 | AlternativesSchema
710 | BinarySchema
711 | BooleanSchema
712 | DateSchema
713 | FunctionSchema
714 | NumberSchema
715 | ObjectSchema
716 | StringSchema
717 | LinkSchema
718 | SymbolSchema;
719
720 type SchemaFunction = (schema: Schema) => Schema;
721
722 interface AddRuleOptions {
723 name: string;
724 args?: {
725 [key: string]: any;
726 } | undefined;
727 }
728
729 interface GetRuleOptions {
730 args?: Record<string, any> | undefined;
731 method?: string | undefined;
732 name: string;
733 operator?: string | undefined;
734 }
735
736 interface SchemaInternals {
737 /**
738 * Parent schema object.
739 */
740 $_super: Schema;
741
742 /**
743 * Terms of current schema.
744 */
745 $_terms: Record<string, any>;
746
747 /**
748 * Adds a rule to current validation schema.
749 */
750 $_addRule(rule: string | AddRuleOptions): Schema;
751
752 /**
753 * Internally compiles schema.
754 */
755 $_compile(schema: SchemaLike, options?: CompileOptions): Schema;
756
757 /**
758 * Creates a joi error object.
759 */
760 $_createError(
761 code: string,
762 value: any,
763 context: Context,
764 state: State,
765 prefs: ValidationOptions,
766 options?: CreateErrorOptions,
767 ): Err;
768
769 /**
770 * Get value from given flag.
771 */
772 $_getFlag(name: string): any;
773
774 /**
775 * Retrieve some rule configuration.
776 */
777 $_getRule(name: string): GetRuleOptions | undefined;
778
779 $_mapLabels(path: string | string[]): string;
780
781 /**
782 * Returns true if validations runs fine on given value.
783 */
784 $_match(value: any, state: State, prefs: ValidationOptions): boolean;
785
786 $_modify(options?: ModifyOptions): Schema;
787
788 /**
789 * Resets current schema.
790 */
791 $_mutateRebuild(): this;
792
793 $_mutateRegister(schema: Schema, options?: MutateRegisterOptions): void;
794
795 /**
796 * Get value from given property.
797 */
798 $_property(name: string): any;
799
800 /**
801 * Get schema at given path.
802 */
803 $_reach(path: string[]): Schema;
804
805 /**
806 * Get current schema root references.
807 */
808 $_rootReferences(): any;
809
810 /**
811 * Set flag to given value.
812 */
813 $_setFlag(flag: string, value: any, options?: SetFlagOptions): void;
814
815 /**
816 * Runs internal validations against given value.
817 */
818 $_validate(value: any, state: State, prefs: ValidationOptions): ValidationResult;
819 }
820
821 interface AnySchema extends SchemaInternals {
822 /**
823 * Flags of current schema.
824 */
825 _flags: Record<string, any>;
826
827 /**
828 * Starts a ruleset in order to apply multiple rule options. The set ends when `rule()`, `keep()`, `message()`, or `warn()` is called.
829 */
830 $: this;
831
832 /**
833 * Starts a ruleset in order to apply multiple rule options. The set ends when `rule()`, `keep()`, `message()`, or `warn()` is called.
834 */
835 ruleset: this;
836
837 type?: Types | string | undefined;
838
839 /**
840 * Whitelists a value
841 */
842 allow(...values: any[]): this;
843
844 /**
845 * Assign target alteration options to a schema that are applied when `any.tailor()` is called.
846 * @param targets - an object where each key is a target name, and each value is a function that takes an schema and returns an schema.
847 */
848 alter(targets: Record<string, SchemaFunction>): this;
849
850 /**
851 * By default, some Joi methods to function properly need to rely on the Joi instance they are attached to because
852 * they use `this` internally.
853 * So `Joi.string()` works but if you extract the function from it and call `string()` it won't.
854 * `bind()` creates a new Joi instance where all the functions relying on `this` are bound to the Joi instance.
855 */
856 bind(): this;
857
858 /**
859 * Adds caching to the schema which will attempt to cache the validation results (success and failures) of incoming inputs.
860 * If no cache is passed, a default cache is provisioned by using `cache.provision()` internally.
861 */
862 cache(cache?: Cache): this;
863
864 /**
865 * Casts the validated value to the specified type.
866 */
867 cast(to: 'map' | 'number' | 'set' | 'string'): this;
868
869 /**
870 * Returns a new type that is the result of adding the rules of one type to another.
871 */
872 concat(schema: this): this;
873
874 /**
875 * Adds a custom validation function.
876 */
877 custom(fn: CustomValidator, description?: string): this;
878
879 /**
880 * Sets a default value if the original value is `undefined` where:
881 * @param value - the default value. One of:
882 * - a literal value (string, number, object, etc.)
883 * - a [references](#refkey-options)
884 * - a function which returns the default value using the signature `function(parent, helpers)` where:
885 * - `parent` - a clone of the object containing the value being validated. Note that since specifying a
886 * `parent` ragument performs cloning, do not declare format arguments if you are not using them.
887 * - `helpers` - same as thsoe described in [`any.custom()`](anycustomermethod_description)
888 *
889 * When called without any `value` on an object schema type, a default value will be automatically generated
890 * based on the default values of the object keys.
891 *
892 * Note that if value is an object, any changes to the object after `default()` is called will change the
893 * reference and any future assignment.
894 */
895 default(value?: BasicType|Reference|((parent: any, helpers: CustomHelpers) => BasicType|Reference)): this;
896
897 /**
898 * Returns a plain object representing the schema's rules and properties
899 */
900 describe(): Description;
901
902 /**
903 * Annotates the key
904 */
905 description(desc: string): this;
906
907 /**
908 * Disallows values.
909 */
910 disallow(...values: any[]): this;
911
912 /**
913 * Considers anything that matches the schema to be empty (undefined).
914 * @param schema - any object or joi schema to match. An undefined schema unsets that rule.
915 */
916 empty(schema?: SchemaLike): this;
917
918 /**
919 * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
920 */
921 equal(...values: any[]): this;
922
923 /**
924 * Overrides the default joi error with a custom error if the rule fails where:
925 * @param err - can be:
926 * an instance of `Error` - the override error.
927 * a `function(errors)`, taking an array of errors as argument, where it must either:
928 * return a `string` - substitutes the error message with this text
929 * return a single ` object` or an `Array` of it, where:
930 * `type` - optional parameter providing the type of the error (eg. `number.min`).
931 * `message` - optional parameter if `template` is provided, containing the text of the error.
932 * `template` - optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors.
933 * `context` - optional parameter, to provide context to your error if you are using the `template`.
934 * return an `Error` - same as when you directly provide an `Error`, but you can customize the error message based on the errors.
935 *
936 * Note that if you provide an `Error`, it will be returned as-is, unmodified and undecorated with any of the
937 * normal joi error properties. If validation fails and another error is found before the error
938 * override, that error will be returned and the override will be ignored (unless the `abortEarly`
939 * option has been set to `false`).
940 */
941 error(err: Error | ValidationErrorFunction): this;
942
943 /**
944 * Annotates the key with an example value, must be valid.
945 */
946 example(value: any, options?: { override: boolean }): this;
947
948 /**
949 * Marks a key as required which will not allow undefined as value. All keys are optional by default.
950 */
951 exist(): this;
952
953 /**
954 * Adds an external validation rule.
955 *
956 * Note that external validation rules are only called after the all other validation rules for the entire schema (from the value root) are checked.
957 * This means that any changes made to the value by the external rules are not available to any other validation rules during the non-external validation phase.
958 * If schema validation failed, no external validation rules are called.
959 */
960 external(method: ExternalValidationFunction, description?: string): this;
961
962 /**
963 * Returns a sub-schema based on a path of object keys or schema ids.
964 *
965 * @param path - a dot `.` separated path string or a pre-split array of path keys. The keys must match the sub-schema id or object key (if no id was explicitly set).
966 */
967 extract(path: string | string[]): Schema;
968
969 /**
970 * Sets a failover value if the original value fails passing validation.
971 *
972 * @param value - the failover value. value supports references. value may be assigned a function which returns the default value.
973 *
974 * 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.
975 * Note that if value is an object, any changes to the object after `failover()` is called will change the reference and any future assignment.
976 * Use a function when setting a dynamic value (e.g. the current time).
977 * Using a function with a single argument performs some internal cloning which has a performance impact.
978 * If you do not need access to the context, define the function without any arguments.
979 */
980 failover(value: any): this;
981
982 /**
983 * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys.
984 */
985 forbidden(): this;
986
987 /**
988 * Returns a new schema where each of the path keys listed have been modified.
989 *
990 * @param key - an array of key strings, a single key string, or an array of arrays of pre-split key strings.
991 * @param adjuster - a function which must return a modified schema.
992 */
993 fork(key: string | string[] | string[][], adjuster: SchemaFunction): this;
994
995 /**
996 * Sets a schema id for reaching into the schema via `any.extract()`.
997 * If no id is set, the schema id defaults to the object key it is associated with.
998 * If the schema is used in an array or alternatives type and no id is set, the schema in unreachable.
999 */
1000 id(name?: string): this;
1001
1002 /**
1003 * Disallows values.
1004 */
1005 invalid(...values: any[]): this;
1006
1007 /**
1008 * Same as `rule({ keep: true })`.
1009 *
1010 * Note that `keep()` will terminate the current ruleset and cannot be followed by another rule option.
1011 * Use `rule()` to apply multiple rule options.
1012 */
1013 keep(): this;
1014
1015 /**
1016 * Overrides the key name in error messages.
1017 */
1018 label(name: string): this;
1019
1020 /**
1021 * Same as `rule({ message })`.
1022 *
1023 * Note that `message()` will terminate the current ruleset and cannot be followed by another rule option.
1024 * Use `rule()` to apply multiple rule options.
1025 */
1026 message(message: string): this;
1027
1028 /**
1029 * Same as `any.prefs({ messages })`.
1030 * Note that while `any.message()` applies only to the last rule or ruleset, `any.messages()` applies to the entire schema.
1031 */
1032 messages(messages: LanguageMessages): this;
1033
1034 /**
1035 * Attaches metadata to the key.
1036 */
1037 meta(meta: object): this;
1038
1039 /**
1040 * Disallows values.
1041 */
1042 not(...values: any[]): this;
1043
1044 /**
1045 * Annotates the key
1046 */
1047 note(...notes: string[]): this;
1048
1049 /**
1050 * Requires the validated value to match of the provided `any.allow()` values.
1051 * It has not effect when called together with `any.valid()` since it already sets the requirements.
1052 * When used with `any.allow()` it converts it to an `any.valid()`.
1053 */
1054 only(): this;
1055
1056 /**
1057 * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default.
1058 */
1059 optional(): this;
1060
1061 /**
1062 * Overrides the global validate() options for the current key and any sub-key.
1063 */
1064 options(options: ValidationOptions): this;
1065
1066 /**
1067 * Overrides the global validate() options for the current key and any sub-key.
1068 */
1069 prefs(options: ValidationOptions): this;
1070
1071 /**
1072 * Overrides the global validate() options for the current key and any sub-key.
1073 */
1074 preferences(options: ValidationOptions): this;
1075
1076 /**
1077 * Sets the presence mode for the schema.
1078 */
1079 presence(mode: PresenceMode): this;
1080
1081 /**
1082 * Outputs the original untouched value instead of the casted value.
1083 */
1084 raw(enabled?: boolean): this;
1085
1086 /**
1087 * Marks a key as required which will not allow undefined as value. All keys are optional by default.
1088 */
1089 required(): this;
1090
1091 /**
1092 * Applies a set of rule options to the current ruleset or last rule added.
1093 *
1094 * When applying rule options, the last rule (e.g. `min()`) is used unless there is an active ruleset defined (e.g. `$.min().max()`)
1095 * in which case the options are applied to all the provided rules.
1096 * Once `rule()` is called, the previous rules can no longer be modified and any active ruleset is terminated.
1097 *
1098 * Rule modifications can only be applied to supported rules.
1099 * Most of the `any` methods do not support rule modifications because they are implemented using schema flags (e.g. `required()`) or special
1100 * internal implementation (e.g. `valid()`).
1101 * In those cases, use the `any.messages()` method to override the error codes for the errors you want to customize.
1102 */
1103 rule(options: RuleOptions): this;
1104
1105 /**
1106 * Registers a schema to be used by decendents of the current schema in named link references.
1107 */
1108 shared(ref: Schema): this;
1109
1110 /**
1111 * Sets the options.convert options to false which prevent type casting for the current key and any child keys.
1112 */
1113 strict(isStrict?: boolean): this;
1114
1115 /**
1116 * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output.
1117 * @param [enabled=true] - if true, the value is stripped, otherwise the validated value is retained. Defaults to true.
1118 */
1119 strip(enabled?: boolean): this;
1120
1121 /**
1122 * Annotates the key
1123 */
1124 tag(...tags: string[]): this;
1125
1126 /**
1127 * Applies any assigned target alterations to a copy of the schema that were applied via `any.alter()`.
1128 */
1129 tailor(targets: string | string[]): Schema;
1130
1131 /**
1132 * Annotates the key with a unit name.
1133 */
1134 unit(name: string): this;
1135
1136 /**
1137 * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
1138 */
1139 valid(...values: any[]): this;
1140
1141 /**
1142 * Validates a value using the schema and options.
1143 */
1144 validate(value: any, options?: ValidationOptions): ValidationResult;
1145
1146 /**
1147 * Validates a value using the schema and options.
1148 */
1149 validateAsync(value: any, options?: AsyncValidationOptions): Promise<any>;
1150
1151 /**
1152 * Same as `rule({ warn: true })`.
1153 * Note that `warn()` will terminate the current ruleset and cannot be followed by another rule option.
1154 * Use `rule()` to apply multiple rule options.
1155 */
1156 warn(): this;
1157
1158 /**
1159 * Generates a warning.
1160 * When calling `any.validateAsync()`, set the `warning` option to true to enable warnings.
1161 * Warnings are reported separately from errors alongside the result value via the warning key (i.e. `{ value, warning }`).
1162 * Warning are always included when calling `any.validate()`.
1163 */
1164 warning(code: string, context: Context): this;
1165
1166 /**
1167 * Converts the type into an alternatives type where the conditions are merged into the type definition where:
1168 */
1169 when(ref: string | Reference, options: WhenOptions): this;
1170
1171 /**
1172 * Converts the type into an alternatives type where the conditions are merged into the type definition where:
1173 */
1174 when(ref: Schema, options: WhenSchemaOptions): this;
1175 }
1176
1177 interface Description {
1178 type?: Types | string | undefined;
1179 label?: string | undefined;
1180 description?: string | undefined;
1181 flags?: object | undefined;
1182 notes?: string[] | undefined;
1183 tags?: string[] | undefined;
1184 meta?: any[] | undefined;
1185 example?: any[] | undefined;
1186 valids?: any[] | undefined;
1187 invalids?: any[] | undefined;
1188 unit?: string | undefined;
1189 options?: ValidationOptions | undefined;
1190 [key: string]: any;
1191 }
1192
1193 interface Context {
1194 [key: string]: any;
1195 key?: string | undefined;
1196 label?: string | undefined;
1197 value?: any;
1198 }
1199
1200 interface State {
1201 key?: string | undefined;
1202 path?: string | undefined;
1203 parent?: any;
1204 reference?: any;
1205 ancestors?: any;
1206 localize?(...args: any[]): State;
1207 }
1208
1209 interface BooleanSchema extends AnySchema {
1210 /**
1211 * Allows for additional values to be considered valid booleans by converting them to false during validation.
1212 * String comparisons are by default case insensitive,
1213 * see `boolean.sensitive()` to change this behavior.
1214 * @param values - strings, numbers or arrays of them
1215 */
1216 falsy(...values: Array<string | number>): this;
1217
1218 /**
1219 * Allows the values provided to truthy and falsy as well as the "true" and "false" default conversion
1220 * (when not in `strict()` mode) to be matched in a case insensitive manner.
1221 */
1222 sensitive(enabled?: boolean): this;
1223
1224 /**
1225 * Allows for additional values to be considered valid booleans by converting them to true during validation.
1226 * String comparisons are by default case insensitive, see `boolean.sensitive()` to change this behavior.
1227 * @param values - strings, numbers or arrays of them
1228 */
1229 truthy(...values: Array<string | number>): this;
1230 }
1231
1232 interface NumberSchema extends AnySchema {
1233 /**
1234 * Specifies that the value must be greater than limit.
1235 * It can also be a reference to another field.
1236 */
1237 greater(limit: number | Reference): this;
1238
1239 /**
1240 * Requires the number to be an integer (no floating point).
1241 */
1242 integer(): this;
1243
1244 /**
1245 * Specifies that the value must be less than limit.
1246 * It can also be a reference to another field.
1247 */
1248 less(limit: number | Reference): this;
1249
1250 /**
1251 * Specifies the maximum value.
1252 * It can also be a reference to another field.
1253 */
1254 max(limit: number | Reference): this;
1255
1256 /**
1257 * Specifies the minimum value.
1258 * It can also be a reference to another field.
1259 */
1260 min(limit: number | Reference): this;
1261
1262 /**
1263 * Specifies that the value must be a multiple of base.
1264 */
1265 multiple(base: number | Reference): this;
1266
1267 /**
1268 * Requires the number to be negative.
1269 */
1270 negative(): this;
1271
1272 /**
1273 * Requires the number to be a TCP port, so between 0 and 65535.
1274 */
1275 port(): this;
1276
1277 /**
1278 * Requires the number to be positive.
1279 */
1280 positive(): this;
1281
1282 /**
1283 * Specifies the maximum number of decimal places where:
1284 * @param limit - the maximum number of decimal places allowed.
1285 */
1286 precision(limit: number): this;
1287
1288 /**
1289 * Requires the number to be negative or positive.
1290 */
1291 sign(sign: 'positive' | 'negative'): this;
1292
1293 /**
1294 * Allows the number to be outside of JavaScript's safety range (Number.MIN_SAFE_INTEGER & Number.MAX_SAFE_INTEGER).
1295 */
1296 unsafe(enabled?: any): this;
1297 }
1298
1299 interface StringSchema extends AnySchema {
1300 /**
1301 * Requires the string value to only contain a-z, A-Z, and 0-9.
1302 */
1303 alphanum(): this;
1304
1305 /**
1306 * Requires the string value to be a valid base64 string; does not check the decoded value.
1307 */
1308 base64(options?: Base64Options): this;
1309
1310 /**
1311 * Sets the required string case.
1312 */
1313 case(direction: 'upper' | 'lower'): this;
1314
1315 /**
1316 * Requires the number to be a credit card number (Using Lunh Algorithm).
1317 */
1318 creditCard(): this;
1319
1320 /**
1321 * Requires the string value to be a valid data URI string.
1322 */
1323 dataUri(options?: DataUriOptions): this;
1324
1325 /**
1326 * Requires the string value to be a valid domain.
1327 */
1328 domain(options?: DomainOptions): this;
1329
1330 /**
1331 * Requires the string value to be a valid email address.
1332 */
1333 email(options?: EmailOptions): this;
1334
1335 /**
1336 * Requires the string value to be a valid GUID.
1337 */
1338 guid(options?: GuidOptions): this;
1339
1340 /**
1341 * Requires the string value to be a valid hexadecimal string.
1342 */
1343 hex(options?: HexOptions): this;
1344
1345 /**
1346 * Requires the string value to be a valid hostname as per RFC1123.
1347 */
1348 hostname(): this;
1349
1350 /**
1351 * Allows the value to match any whitelist of blacklist item in a case insensitive comparison.
1352 */
1353 insensitive(): this;
1354
1355 /**
1356 * Requires the string value to be a valid ip address.
1357 */
1358 ip(options?: IpOptions): this;
1359
1360 /**
1361 * Requires the string value to be in valid ISO 8601 date format.
1362 */
1363 isoDate(): this;
1364
1365 /**
1366 * Requires the string value to be in valid ISO 8601 duration format.
1367 */
1368 isoDuration(): this;
1369
1370 /**
1371 * Specifies the exact string length required
1372 * @param limit - the required string length. It can also be a reference to another field.
1373 * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
1374 */
1375 length(limit: number | Reference, encoding?: string): this;
1376
1377 /**
1378 * Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase.
1379 */
1380 lowercase(): this;
1381
1382 /**
1383 * Specifies the maximum number of string characters.
1384 * @param limit - the maximum number of string characters allowed. It can also be a reference to another field.
1385 * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
1386 */
1387 max(limit: number | Reference, encoding?: string): this;
1388
1389 /**
1390 * Specifies the minimum number string characters.
1391 * @param limit - the minimum number of string characters required. It can also be a reference to another field.
1392 * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
1393 */
1394 min(limit: number | Reference, encoding?: string): this;
1395
1396 /**
1397 * Requires the string value to be in a unicode normalized form. If the validation convert option is on (enabled by default), the string will be normalized.
1398 * @param [form='NFC'] - The unicode normalization form to use. Valid values: NFC [default], NFD, NFKC, NFKD
1399 */
1400 normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this;
1401
1402 /**
1403 * Defines a regular expression rule.
1404 * @param pattern - a regular expression object the string value must match against.
1405 * @param options - optional, can be:
1406 * Name for patterns (useful with multiple patterns). Defaults to 'required'.
1407 * An optional configuration object with the following supported properties:
1408 * name - optional pattern name.
1409 * invert - optional boolean flag. Defaults to false behavior. If specified as true, the provided pattern will be disallowed instead of required.
1410 */
1411 pattern(pattern: RegExp, options?: string | StringRegexOptions): this;
1412
1413 /**
1414 * Defines a regular expression rule.
1415 * @param pattern - a regular expression object the string value must match against.
1416 * @param options - optional, can be:
1417 * Name for patterns (useful with multiple patterns). Defaults to 'required'.
1418 * An optional configuration object with the following supported properties:
1419 * name - optional pattern name.
1420 * invert - optional boolean flag. Defaults to false behavior. If specified as true, the provided pattern will be disallowed instead of required.
1421 */
1422 regex(pattern: RegExp, options?: string | StringRegexOptions): this;
1423
1424 /**
1425 * Replace characters matching the given pattern with the specified replacement string where:
1426 * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced.
1427 * @param replacement - the string that will replace the pattern.
1428 */
1429 replace(pattern: RegExp | string, replacement: string): this;
1430
1431 /**
1432 * Requires the string value to only contain a-z, A-Z, 0-9, and underscore _.
1433 */
1434 token(): this;
1435
1436 /**
1437 * Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed.
1438 * @param [enabled=true] - optional parameter defaulting to true which allows you to reset the behavior of trim by providing a falsy value.
1439 */
1440 trim(enabled?: any): this;
1441
1442 /**
1443 * Specifies whether the string.max() limit should be used as a truncation.
1444 * @param [enabled=true] - optional parameter defaulting to true which allows you to reset the behavior of truncate by providing a falsy value.
1445 */
1446 truncate(enabled?: boolean): this;
1447
1448 /**
1449 * Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase.
1450 */
1451 uppercase(): this;
1452
1453 /**
1454 * Requires the string value to be a valid RFC 3986 URI.
1455 */
1456 uri(options?: UriOptions): this;
1457
1458 /**
1459 * Requires the string value to be a valid GUID.
1460 */
1461 uuid(options?: GuidOptions): this;
1462 }
1463
1464 interface SymbolSchema extends AnySchema {
1465 // TODO: support number and symbol index
1466 map(iterable: Iterable<[string | number | boolean | symbol, symbol]> | { [key: string]: symbol }): this;
1467 }
1468
1469 interface ArraySortOptions {
1470 /**
1471 * @default 'ascending'
1472 */
1473 order?: 'ascending' | 'descending' | undefined;
1474 by?: string | Reference | undefined;
1475 }
1476
1477 interface ArrayUniqueOptions extends HierarchySeparatorOptions {
1478 /**
1479 * if true, undefined values for the dot notation string comparator will not cause the array to fail on uniqueness.
1480 *
1481 * @default false
1482 */
1483 ignoreUndefined?: boolean | undefined;
1484 }
1485
1486 type ComparatorFunction = (a: any, b: any) => boolean;
1487
1488 interface ArraySchema extends AnySchema {
1489 /**
1490 * Verifies that an assertion passes for at least one item in the array, where:
1491 * `schema` - the validation rules required to satisfy the assertion. If the `schema` includes references, they are resolved against
1492 * the array item being tested, not the value of the `ref` target.
1493 */
1494 has(schema: SchemaLike): this;
1495
1496 /**
1497 * List the types allowed for the array values.
1498 * If a given type is .required() then there must be a matching item in the array.
1499 * If a type is .forbidden() then it cannot appear in the array.
1500 * Required items can be added multiple times to signify that multiple items must be found.
1501 * Errors will contain the number of items that didn't match.
1502 * Any unmatched item having a label will be mentioned explicitly.
1503 *
1504 * @param type - a joi schema object to validate each array item against.
1505 */
1506 items(...types: SchemaLike[]): this;
1507
1508 /**
1509 * Specifies the exact number of items in the array.
1510 */
1511 length(limit: number | Reference): this;
1512
1513 /**
1514 * Specifies the maximum number of items in the array.
1515 */
1516 max(limit: number | Reference): this;
1517
1518 /**
1519 * Specifies the minimum number of items in the array.
1520 */
1521 min(limit: number | Reference): this;
1522
1523 /**
1524 * Lists the types in sequence order for the array values where:
1525 * @param type - a joi schema object to validate against each array item in sequence order. type can be multiple values passed as individual arguments.
1526 * If a given type is .required() then there must be a matching item with the same index position in the array.
1527 * Errors will contain the number of items that didn't match.
1528 * Any unmatched item having a label will be mentioned explicitly.
1529 */
1530 ordered(...types: SchemaLike[]): this;
1531
1532 /**
1533 * Allow single values to be checked against rules as if it were provided as an array.
1534 * enabled can be used with a falsy value to go back to the default behavior.
1535 */
1536 single(enabled?: any): this;
1537
1538 /**
1539 * Sorts the array by given order.
1540 */
1541 sort(options?: ArraySortOptions): this;
1542
1543 /**
1544 * Allow this array to be sparse.
1545 * enabled can be used with a falsy value to go back to the default behavior.
1546 */
1547 sparse(enabled?: any): this;
1548
1549 /**
1550 * Requires the array values to be unique.
1551 * Remember that if you provide a custom comparator function,
1552 * different types can be passed as parameter depending on the rules you set on items.
1553 * Be aware that a deep equality is performed on elements of the array having a type of object,
1554 * a performance penalty is to be expected for this kind of operation.
1555 */
1556 unique(comparator?: string | ComparatorFunction, options?: ArrayUniqueOptions): this;
1557 }
1558
1559 interface ObjectPatternOptions {
1560 fallthrough?: boolean | undefined;
1561 matches: SchemaLike | Reference;
1562 }
1563
1564 interface ObjectSchema<TSchema = any> extends AnySchema {
1565 /**
1566 * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well.
1567 *
1568 * Optional settings must be the last argument.
1569 */
1570 and(...peers: Array<string | HierarchySeparatorOptions>): this;
1571
1572 /**
1573 * Appends the allowed object keys. If schema is null, undefined, or {}, no changes will be applied.
1574 */
1575 append(schema?: SchemaMap<TSchema>): this;
1576
1577 /**
1578 * Verifies an assertion where.
1579 */
1580 assert(ref: string | Reference, schema: SchemaLike, message?: string): this;
1581
1582 /**
1583 * Requires the object to be an instance of a given constructor.
1584 *
1585 * @param constructor - the constructor function that the object must be an instance of.
1586 * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name.
1587 */
1588 // tslint:disable-next-line:ban-types
1589 instance(constructor: Function, name?: string): this;
1590
1591 /**
1592 * Sets or extends the allowed object keys.
1593 */
1594 keys(schema?: SchemaMap<TSchema>): this;
1595
1596 /**
1597 * Specifies the exact number of keys in the object.
1598 */
1599 length(limit: number): this;
1600
1601 /**
1602 * Specifies the maximum number of keys in the object.
1603 */
1604 max(limit: number | Reference): this;
1605
1606 /**
1607 * Specifies the minimum number of keys in the object.
1608 */
1609 min(limit: number | Reference): this;
1610
1611 /**
1612 * Defines a relationship between keys where not all peers can be present at the same time.
1613 *
1614 * Optional settings must be the last argument.
1615 */
1616 nand(...peers: Array<string | HierarchySeparatorOptions>): this;
1617
1618 /**
1619 * Defines a relationship between keys where one of the peers is required (and more than one is allowed).
1620 *
1621 * Optional settings must be the last argument.
1622 */
1623 or(...peers: Array<string | HierarchySeparatorOptions>): this;
1624
1625 /**
1626 * Defines an exclusive relationship between a set of keys where only one is allowed but none are required.
1627 *
1628 * Optional settings must be the last argument.
1629 */
1630 oxor(...peers: Array<string | HierarchySeparatorOptions>): this;
1631
1632 /**
1633 * Specify validation rules for unknown keys matching a pattern.
1634 *
1635 * @param pattern - a pattern that can be either a regular expression or a joi schema that will be tested against the unknown key names
1636 * @param schema - the schema object matching keys must validate against
1637 */
1638 pattern(pattern: RegExp | SchemaLike, schema: SchemaLike, options?: ObjectPatternOptions): this;
1639
1640 /**
1641 * Requires the object to be a Joi reference.
1642 */
1643 ref(): this;
1644
1645 /**
1646 * Requires the object to be a `RegExp` object.
1647 */
1648 regex(): this;
1649
1650 /**
1651 * Renames a key to another name (deletes the renamed key).
1652 */
1653 rename(from: string | RegExp, to: string, options?: RenameOptions): this;
1654
1655 /**
1656 * Requires the object to be a Joi schema instance.
1657 */
1658 schema(type?: SchemaLike): this;
1659
1660 /**
1661 * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children).
1662 */
1663 unknown(allow?: boolean): this;
1664
1665 /**
1666 * Requires the presence of other keys whenever the specified key is present.
1667 */
1668 with(key: string, peers: string | string[], options?: HierarchySeparatorOptions): this;
1669
1670 /**
1671 * Forbids the presence of other keys whenever the specified is present.
1672 */
1673 without(key: string, peers: string | string[], options?: HierarchySeparatorOptions): this;
1674
1675 /**
1676 * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time.
1677 *
1678 * Optional settings must be the last argument.
1679 */
1680 xor(...peers: Array<string | HierarchySeparatorOptions>): this;
1681 }
1682
1683 interface BinarySchema extends AnySchema {
1684 /**
1685 * Sets the string encoding format if a string input is converted to a buffer.
1686 */
1687 encoding(encoding: string): this;
1688
1689 /**
1690 * Specifies the minimum length of the buffer.
1691 */
1692 min(limit: number | Reference): this;
1693
1694 /**
1695 * Specifies the maximum length of the buffer.
1696 */
1697 max(limit: number | Reference): this;
1698
1699 /**
1700 * Specifies the exact length of the buffer:
1701 */
1702 length(limit: number | Reference): this;
1703 }
1704
1705 interface DateSchema extends AnySchema {
1706 /**
1707 * Specifies that the value must be greater than date.
1708 * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
1709 * allowing to explicitly ensure a date is either in the past or in the future.
1710 * It can also be a reference to another field.
1711 */
1712 greater(date: 'now' | Date | number | string | Reference): this;
1713
1714 /**
1715 * Requires the string value to be in valid ISO 8601 date format.
1716 */
1717 iso(): this;
1718
1719 /**
1720 * Specifies that the value must be less than date.
1721 * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
1722 * allowing to explicitly ensure a date is either in the past or in the future.
1723 * It can also be a reference to another field.
1724 */
1725 less(date: 'now' | Date | number | string | Reference): this;
1726
1727 /**
1728 * Specifies the oldest date allowed.
1729 * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
1730 * allowing to explicitly ensure a date is either in the past or in the future.
1731 * It can also be a reference to another field.
1732 */
1733 min(date: 'now' | Date | number | string | Reference): this;
1734
1735 /**
1736 * Specifies the latest date allowed.
1737 * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
1738 * allowing to explicitly ensure a date is either in the past or in the future.
1739 * It can also be a reference to another field.
1740 */
1741 max(date: 'now' | Date | number | string | Reference): this;
1742
1743 /**
1744 * Requires the value to be a timestamp interval from Unix Time.
1745 * @param type - the type of timestamp (allowed values are unix or javascript [default])
1746 */
1747 timestamp(type?: 'javascript' | 'unix'): this;
1748 }
1749
1750 interface FunctionSchema extends ObjectSchema {
1751 /**
1752 * Specifies the arity of the function where:
1753 * @param n - the arity expected.
1754 */
1755 arity(n: number): this;
1756
1757 /**
1758 * Requires the function to be a class.
1759 */
1760 class(): this;
1761
1762 /**
1763 * Specifies the minimal arity of the function where:
1764 * @param n - the minimal arity expected.
1765 */
1766 minArity(n: number): this;
1767
1768 /**
1769 * Specifies the minimal arity of the function where:
1770 * @param n - the minimal arity expected.
1771 */
1772 maxArity(n: number): this;
1773 }
1774
1775 interface AlternativesSchema extends AnySchema {
1776 /**
1777 * Adds a conditional alternative schema type, either based on another key value, or a schema peeking into the current value.
1778 */
1779 conditional(ref: string | Reference, options: WhenOptions): this;
1780 conditional(ref: Schema, options: WhenSchemaOptions): this;
1781
1782 /**
1783 * Requires the validated value to match a specific set of the provided alternative.try() schemas.
1784 * Cannot be combined with `alternatives.conditional()`.
1785 */
1786 match(mode: 'any' | 'all' | 'one'): this;
1787
1788 /**
1789 * Adds an alternative schema type for attempting to match against the validated value.
1790 */
1791 try(...types: SchemaLike[]): this;
1792 }
1793
1794 interface LinkSchema extends AnySchema {
1795 /**
1796 * Same as `any.concat()` but the schema is merged after the link is resolved which allows merging with schemas of the same type as the resolved link.
1797 * Will throw an exception during validation if the merged types are not compatible.
1798 */
1799 concat(schema: Schema): this;
1800
1801 /**
1802 * Initializes the schema after constructions for cases where the schema has to be constructed first and then initialized.
1803 * If `ref` was not passed to the constructor, `link.ref()` must be called prior to usaged.
1804 */
1805 ref(ref: string): this;
1806 }
1807
1808 interface Reference extends Exclude<ReferenceOptions, 'prefix'> {
1809 depth: number;
1810 type: string;
1811 key: string;
1812 root: string;
1813 path: string[];
1814 display: string;
1815 toString(): string;
1816 }
1817
1818 type ExtensionBoundSchema = Schema & SchemaInternals;
1819
1820 interface RuleArgs {
1821 name: string;
1822 ref?: boolean | undefined;
1823 assert?: ((value: any) => boolean) | AnySchema | undefined;
1824 message?: string | undefined;
1825
1826 /**
1827 * Undocumented properties
1828 */
1829 normalize?(value: any): any;
1830 }
1831
1832 type RuleMethod = (...args: any[]) => any;
1833
1834 interface ExtensionRule {
1835 /**
1836 * alternative name for this rule.
1837 */
1838 alias?: string | undefined;
1839 /**
1840 * whether rule supports multiple invocations.
1841 */
1842 multi?: boolean | undefined;
1843 /**
1844 * Dual rule: converts or validates.
1845 */
1846 convert?: boolean | undefined;
1847 /**
1848 * list of arguments accepted by `method`.
1849 */
1850 args?: Array<RuleArgs | string> | undefined;
1851 /**
1852 * rule body.
1853 */
1854 method?: RuleMethod | false | undefined;
1855 /**
1856 * validation function.
1857 */
1858 validate?(value: any, helpers: any, args: Record<string, any>, options: any): any;
1859
1860 /**
1861 * undocumented flags.
1862 */
1863 priority?: boolean | undefined;
1864 manifest?: boolean | undefined;
1865 }
1866
1867 interface CoerceResult {
1868 errors?: ErrorReport[] | undefined;
1869 value?: any;
1870 }
1871
1872 type CoerceFunction = (value: any, helpers: CustomHelpers) => CoerceResult;
1873
1874 interface CoerceObject {
1875 method: CoerceFunction;
1876 from?: string | string[] | undefined;
1877 }
1878
1879 interface ExtensionFlag {
1880 setter?: string | undefined;
1881 default?: any;
1882 }
1883
1884 interface ExtensionTermManifest {
1885 mapped: {
1886 from: string;
1887 to: string;
1888 };
1889 }
1890
1891 interface ExtensionTerm {
1892 init: any[] | null;
1893 register?: any;
1894 manifest?: Record<string, 'schema' | 'single' | ExtensionTermManifest> | undefined;
1895 }
1896
1897 interface Extension {
1898 type: string;
1899 args?(...args: SchemaLike[]): Schema;
1900 base?: Schema | undefined;
1901 coerce?: CoerceFunction | CoerceObject | undefined;
1902 flags?: Record<string, ExtensionFlag> | undefined;
1903 manifest?: {
1904 build?(obj: ExtensionBoundSchema, desc: Record<string, any>): any;
1905 } | undefined;
1906 messages?: LanguageMessages | string | undefined;
1907 modifiers?: Record<string, (rule: any, enabled?: boolean) => any> | undefined;
1908 overrides?: Record<string, (value: any) => Schema> | undefined;
1909 prepare?(value: any, helpers: CustomHelpers): any;
1910 rebuild?(schema: ExtensionBoundSchema): void;
1911 rules?: Record<string, ExtensionRule & ThisType<SchemaInternals>> | undefined;
1912 terms?: Record<string, ExtensionTerm> | undefined;
1913 validate?(value: any, helpers: CustomHelpers): any;
1914
1915 /**
1916 * undocumented options
1917 */
1918 cast?: Record<string, { from(value: any): any; to(value: any, helpers: CustomHelpers): any }> | undefined;
1919 properties?: Record<string, any> | undefined;
1920 }
1921
1922 type ExtensionFactory = (joi: Root) => Extension;
1923
1924 interface Err {
1925 toString(): string;
1926 }
1927
1928 // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
1929
1930 interface Root {
1931 /**
1932 * Current version of the joi package.
1933 */
1934 version: string;
1935
1936 ValidationError: new (message: string, details: any, original: any) => ValidationError;
1937
1938 /**
1939 * Generates a schema object that matches any data type.
1940 */
1941 any(): AnySchema;
1942
1943 /**
1944 * Generates a schema object that matches an array data type.
1945 */
1946 array(): ArraySchema;
1947
1948 /**
1949 * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool().
1950 */
1951 bool(): BooleanSchema;
1952
1953 /**
1954 * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool().
1955 */
1956 boolean(): BooleanSchema;
1957
1958 /**
1959 * Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers).
1960 */
1961 binary(): BinarySchema;
1962
1963 /**
1964 * Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds).
1965 */
1966 date(): DateSchema;
1967
1968 /**
1969 * Generates a schema object that matches a function type.
1970 */
1971 func(): FunctionSchema;
1972
1973 /**
1974 * Generates a schema object that matches a function type.
1975 */
1976 function(): FunctionSchema;
1977
1978 /**
1979 * Generates a schema object that matches a number data type (as well as strings that can be converted to numbers).
1980 */
1981 number(): NumberSchema;
1982
1983 /**
1984 * Generates a schema object that matches an object data type (as well as JSON strings that have been parsed into objects).
1985 */
1986 // tslint:disable-next-line:no-unnecessary-generics
1987 object<TSchema = any, T = TSchema>(schema?: SchemaMap<T>): ObjectSchema<TSchema>;
1988
1989 /**
1990 * Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow('').
1991 */
1992 string(): StringSchema;
1993
1994 /**
1995 * Generates a schema object that matches any symbol.
1996 */
1997 symbol(): SymbolSchema;
1998
1999 /**
2000 * Generates a type that will match one of the provided alternative schemas
2001 */
2002 alternatives(types: SchemaLike[]): AlternativesSchema;
2003 alternatives(...types: SchemaLike[]): AlternativesSchema;
2004
2005 /**
2006 * Alias for `alternatives`
2007 */
2008 alt(types: SchemaLike[]): AlternativesSchema;
2009 alt(...types: SchemaLike[]): AlternativesSchema;
2010
2011 /**
2012 * Links to another schema node and reuses it for validation, typically for creative recursive schemas.
2013 *
2014 * @param ref - the reference to the linked schema node.
2015 * Cannot reference itself or its children as well as other links.
2016 * Links can be expressed in relative terms like value references (`Joi.link('...')`),
2017 * in absolute terms from the schema run-time root (`Joi.link('/a')`),
2018 * or using schema ids implicitly using object keys or explicitly using `any.id()` (`Joi.link('#a.b.c')`).
2019 */
2020 link(ref?: string): LinkSchema;
2021
2022 /**
2023 * Validates a value against a schema and throws if validation fails.
2024 *
2025 * @param value - the value to validate.
2026 * @param schema - the schema object.
2027 * @param message - optional message string prefix added in front of the error message. may also be an Error object.
2028 */
2029 assert(value: any, schema: SchemaLike, options?: ValidationOptions): void;
2030 assert(value: any, schema: SchemaLike, message: string | Error, options?: ValidationOptions): void;
2031
2032 /**
2033 * Validates a value against a schema, returns valid object, and throws if validation fails.
2034 *
2035 * @param value - the value to validate.
2036 * @param schema - the schema object.
2037 * @param message - optional message string prefix added in front of the error message. may also be an Error object.
2038 */
2039 attempt(value: any, schema: SchemaLike, options?: ValidationOptions): any;
2040 attempt(value: any, schema: SchemaLike, message: string | Error, options?: ValidationOptions): any;
2041
2042 cache: CacheConfiguration;
2043
2044 /**
2045 * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object).
2046 */
2047 compile(schema: SchemaLike, options?: CompileOptions): Schema;
2048
2049 /**
2050 * Checks if the provided preferences are valid.
2051 *
2052 * Throws an exception if the prefs object is invalid.
2053 *
2054 * The method is provided to perform inputs validation for the `any.validate()` and `any.validateAsync()` methods.
2055 * Validation is not performed automatically for performance reasons. Instead, manually validate the preferences passed once and reuse.
2056 */
2057 checkPreferences(prefs: ValidationOptions): void;
2058
2059 /**
2060 * Creates a custom validation schema.
2061 */
2062 custom(fn: CustomValidator, description?: string): Schema;
2063
2064 /**
2065 * Creates a new Joi instance that will apply defaults onto newly created schemas
2066 * through the use of the fn function that takes exactly one argument, the schema being created.
2067 *
2068 * @param fn - The function must always return a schema, even if untransformed.
2069 */
2070 defaults(fn: SchemaFunction): Root;
2071
2072 /**
2073 * Generates a dynamic expression using a template string.
2074 */
2075 expression(template: string, options?: ReferenceOptions): any;
2076
2077 /**
2078 * Creates a new Joi instance customized with the extension(s) you provide included.
2079 */
2080 extend(...extensions: Array<Extension | ExtensionFactory>): any;
2081
2082 /**
2083 * Creates a reference that when resolved, is used as an array of values to match against the rule.
2084 */
2085 in(ref: string, options?: ReferenceOptions): Reference;
2086
2087 /**
2088 * Checks whether or not the provided argument is an instance of ValidationError
2089 */
2090 isError(error: any): error is ValidationError;
2091
2092 /**
2093 * Checks whether or not the provided argument is an expression.
2094 */
2095 isExpression(expression: any): boolean;
2096
2097 /**
2098 * Checks whether or not the provided argument is a reference. It's especially useful if you want to post-process error messages.
2099 */
2100 isRef(ref: any): ref is Reference;
2101
2102 /**
2103 * Checks whether or not the provided argument is a joi schema.
2104 */
2105 isSchema(schema: any, options?: CompileOptions): boolean;
2106
2107 /**
2108 * A special value used with `any.allow()`, `any.invalid()`, and `any.valid()` as the first value to reset any previously set values.
2109 */
2110 override: symbol;
2111
2112 /**
2113 * Generates a reference to the value of the named key.
2114 */
2115 ref(key: string, options?: ReferenceOptions): Reference;
2116
2117 /**
2118 * Returns an object where each key is a plain joi schema type.
2119 * Useful for creating type shortcuts using deconstruction.
2120 * Note that the types are already formed and do not need to be called as functions (e.g. `string`, not `string()`).
2121 */
2122 types(): {
2123 alternatives: AlternativesSchema;
2124 any: AnySchema;
2125 array: ArraySchema;
2126 binary: BinarySchema;
2127 boolean: BooleanSchema;
2128 date: DateSchema;
2129 function: FunctionSchema;
2130 link: LinkSchema;
2131 number: NumberSchema;
2132 object: ObjectSchema;
2133 string: StringSchema;
2134 symbol: SymbolSchema;
2135 };
2136
2137 /**
2138 * Generates a dynamic expression using a template string.
2139 */
2140 x(template: string, options?: ReferenceOptions): any;
2141
2142 // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
2143 // Below are undocumented APIs. use at your own risk
2144 // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
2145
2146 /**
2147 * Whitelists a value
2148 */
2149 allow(...values: any[]): Schema;
2150
2151 /**
2152 * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed.
2153 */
2154 valid(...values: any[]): Schema;
2155 equal(...values: any[]): Schema;
2156
2157 /**
2158 * Blacklists a value
2159 */
2160 invalid(...values: any[]): Schema;
2161 disallow(...values: any[]): Schema;
2162 not(...values: any[]): Schema;
2163
2164 /**
2165 * Marks a key as required which will not allow undefined as value. All keys are optional by default.
2166 */
2167 required(): Schema;
2168
2169 /**
2170 * Alias of `required`.
2171 */
2172 exist(): Schema;
2173
2174 /**
2175 * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default.
2176 */
2177 optional(): Schema;
2178
2179 /**
2180 * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys.
2181 */
2182 forbidden(): Schema;
2183
2184 /**
2185 * Overrides the global validate() options for the current key and any sub-key.
2186 */
2187 preferences(options: ValidationOptions): Schema;
2188
2189 /**
2190 * Overrides the global validate() options for the current key and any sub-key.
2191 */
2192 prefs(options: ValidationOptions): Schema;
2193
2194 /**
2195 * Converts the type into an alternatives type where the conditions are merged into the type definition where:
2196 */
2197 when(ref: string | Reference, options: WhenOptions): AlternativesSchema;
2198 when(ref: Schema, options: WhenSchemaOptions): AlternativesSchema;
2199
2200 /**
2201 * Unsure, maybe alias for `compile`?
2202 */
2203 build(...args: any[]): any;
2204
2205 /**
2206 * Unsure, maybe alias for `preferences`?
2207 */
2208 options(...args: any[]): any;
2209
2210 /**
2211 * Unsure, maybe leaked from `@hapi/lab/coverage/initialize`
2212 */
2213 trace(...args: any[]): any;
2214 untrace(...args: any[]): any;
2215 }
2216}
2217
2218declare const Joi: Joi.Root;
2219export = Joi;