UNPKG

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