UNPKG

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