@nhtio/validation 0.1.0-master-952eca46 → 0.1.0-master-b4207fd6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,840 +0,0 @@
1
- import type { Knex } from 'knex';
2
- import type { Reference } from '..';
3
- import type { DateTime } from 'luxon';
4
- import type { PhoneSchema } from './schemas/phone';
5
- import type { BigIntSchema } from './schemas/bigint';
6
- import type { DatetimeSchema } from './schemas/datetime';
7
- import type { QueryClientContract } from '@adonisjs/lucid/types/database';
8
- import type { DatabaseQueryBuilderContract } from '@adonisjs/lucid/types/querybuilder';
9
- import type { default as Joi, AnySchema as JoiAnySchema, BasicType, CustomHelpers, ExternalHelpers } from 'joi';
10
- export type { Knex, QueryClientContract, DatabaseQueryBuilderContract };
11
- export type KnexTransaction = Knex.Transaction;
12
- export type KnexQueryBuilder = Knex.QueryBuilder;
13
- export type QueryClient = Knex | KnexTransaction | QueryClientContract;
14
- export type QueryBuilder = KnexQueryBuilder | DatabaseQueryBuilderContract;
15
- export interface KnexConnectionConfigurations {
16
- client: NonNullable<Knex.Config['client']>;
17
- connection: NonNullable<Knex.Config['connection']>;
18
- [key: string | number | symbol]: any;
19
- }
20
- export type KnexSchemaConnection = QueryClient | KnexConnectionConfigurations;
21
- export type DefaultableValue = Reference | BasicType | DateTime | bigint | ((parent: any, helpers: CustomHelpers) => Reference | BasicType | DateTime | bigint);
22
- /**
23
- * Options for database-backed validation helpers such as `uniqueInDb` and `existsInDb`.
24
- */
25
- export interface DbValidationOptions {
26
- /**
27
- * Perform case-insensitive comparisons when querying the database.
28
- * Defaults to `false`.
29
- */
30
- caseInsensitive?: boolean;
31
- /**
32
- * Optional function that receives the Knex query builder (or equivalent) so
33
- * the caller can append additional WHERE clauses (or joins). Can be async.
34
- * Example: `async (query, value, column, helpers) => query.where('tenant_id', tenantId)`
35
- */
36
- filter?: (queryBuilder: QueryBuilder, value: any, column: string, helpers: Omit<ExternalHelpers, 'warn' | 'error' | 'message'>) => void | Promise<void>;
37
- }
38
- /**
39
- * Base schema type for all validation schemas.
40
- *
41
- * This interface provides the foundation for all validation schemas with
42
- * comprehensive validation methods and options.
43
- *
44
- * @public
45
- */
46
- export interface AnySchema<TSchema = any> extends Omit<JoiAnySchema<TSchema>, '$_addRule' | '$_compile' | '$_modify' | '$_mutateRebuild' | '$_reach' | '$_super' | '$' | 'allow' | 'alter' | 'artifact' | 'bind' | 'cache' | 'cast' | 'concat' | 'custom' | 'default' | 'description' | 'disallow' | 'empty' | 'equal' | 'error' | 'example' | 'exist' | 'external' | 'extract' | 'failover' | 'forbidden' | 'fork' | 'id' | 'invalid' | 'keep' | 'label' | 'message' | 'messages' | 'meta' | 'not' | 'note' | 'only' | 'optional' | 'options' | 'preferences' | 'prefs' | 'presence' | 'raw' | 'required' | 'rule' | 'ruleset' | 'shared' | 'strict' | 'strip' | 'tag' | 'tailor' | 'unit' | 'valid' | 'warn' | 'warning' | 'when'> {
47
- /**
48
- * Parent schema object.
49
- */
50
- $_super: Schema;
51
- /**
52
- * Adds a rule to current validation schema.
53
- */
54
- $_addRule(rule: string | Joi.AddRuleOptions): Schema;
55
- /**
56
- * Internally compiles schema.
57
- */
58
- $_compile(schema: SchemaLike, options?: Joi.CompileOptions): Schema;
59
- $_modify(options?: Joi.ModifyOptions): Schema;
60
- /**
61
- * Resets current schema.
62
- */
63
- $_mutateRebuild(): this;
64
- /**
65
- * Get schema at given path.
66
- */
67
- $_reach(path: string[]): Schema;
68
- /**
69
- * Starts a ruleset in order to apply multiple rule options. The set ends when `rule()`, `keep()`, `message()`, or `warn()` is called.
70
- */
71
- $: this;
72
- /**
73
- * Starts a ruleset in order to apply multiple rule options. The set ends when `rule()`, `keep()`, `message()`, or `warn()` is called.
74
- */
75
- ruleset: this;
76
- allow(...values: any[]): this;
77
- alter(targets: Record<string, (schema: this) => Schema>): this;
78
- artifact(id: any): this;
79
- bind(): this;
80
- cache(cache?: Joi.Cache): this;
81
- concat(schema: this): this;
82
- custom(fn: Joi.CustomValidator, description?: string): this;
83
- description(desc: string): this;
84
- disallow(...values: any[]): this;
85
- empty(schema?: SchemaLike): this;
86
- equal(...values: any[]): this;
87
- error(err: Error | Joi.ValidationErrorFunction): this;
88
- example(value: any, options?: {
89
- override: boolean;
90
- }): this;
91
- exist(): this;
92
- external(method: Joi.ExternalValidationFunction, description?: string): this;
93
- /**
94
- * Returns a sub-schema based on a path of object keys or schema ids.
95
- *
96
- * @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).
97
- */
98
- extract(path: string | string[]): Schema;
99
- failover(value: any): this;
100
- forbidden(): this;
101
- fork(key: string | string[] | string[][], adjuster: Joi.SchemaFunction): this;
102
- id(name?: string): this;
103
- invalid(...values: any[]): this;
104
- keep(): this;
105
- label(name: string): this;
106
- message(message: string): this;
107
- messages(messages: Joi.LanguageMessages): this;
108
- meta(meta: object): this;
109
- not(...values: any[]): this;
110
- note(...notes: string[]): this;
111
- only(): this;
112
- optional(): this;
113
- options(options: Joi.ValidationOptions): this;
114
- prefs(options: Joi.ValidationOptions): this;
115
- preferences(options: Joi.ValidationOptions): this;
116
- presence(mode: Joi.PresenceMode): this;
117
- raw(enabled?: boolean): this;
118
- required(): this;
119
- rule(options: Joi.RuleOptions): this;
120
- shared(ref: Schema): this;
121
- strict(isStrict?: boolean): this;
122
- strip(enabled?: boolean): this;
123
- tag(...tags: string[]): this;
124
- /**
125
- * Applies any assigned target alterations to a copy of the schema that were applied via `any.alter()`.
126
- */
127
- tailor(targets: string | string[]): Schema;
128
- unit(name: string): this;
129
- valid(...values: any[]): this;
130
- warn(): this;
131
- warning(code: string, context: Joi.Context): this;
132
- when(ref: string | Reference, options: Joi.WhenOptions | Joi.WhenOptions[]): this;
133
- when(ref: Schema, options: Joi.WhenSchemaOptions): this;
134
- $_knex: KnexSchemaConnection | undefined;
135
- /**
136
- * Sets the database connection for database validation rules.
137
- * This must be called before using `.uniqueInDb()` or `.existsInDb()`.
138
- *
139
- * @param connection - A Knex instance, transaction, or connection configuration
140
- *
141
- * @example
142
- * ```typescript
143
- * import knex from 'knex'
144
- * const db = knex({ client: 'pg', connection: {...} })
145
- * const schema = joi.string().knex(db).uniqueInDb('users', 'email')
146
- * ```
147
- */
148
- knex(connection: KnexSchemaConnection): this;
149
- /**
150
- * Alias for `.knex()`. Sets the database connection for database validation rules.
151
- *
152
- * @param connection - A Knex instance, transaction, or connection configuration
153
- */
154
- db(connection: KnexSchemaConnection): this;
155
- /**
156
- * Validates that the value is unique in the specified database table and column.
157
- * Requires `.knex()` or `.db()` to be called first to set the database connection.
158
- *
159
- * @param table - The database table name (can be a Joi reference)
160
- * @param column - The column name to check (can be a Joi reference)
161
- * @param options - Optional configuration:
162
- * - `caseInsensitive`: Perform case-insensitive comparison (default: false)
163
- * - `filter`: Async function to add additional WHERE clauses to the query
164
- *
165
- * @example
166
- * ```typescript
167
- * const schema = joi.object({
168
- * email: joi.string().email().knex(db).uniqueInDb('users', 'email'),
169
- * username: joi.string().knex(db).uniqueInDb('users', 'username', {
170
- * caseInsensitive: true,
171
- * filter: async (query) => query.where('tenant_id', tenantId)
172
- * })
173
- * })
174
- * ```
175
- */
176
- uniqueInDb(table: string | Reference, column: string | Reference, options?: DbValidationOptions): this;
177
- /**
178
- * Validates that the value exists in the specified database table and column.
179
- * Requires `.knex()` or `.db()` to be called first to set the database connection.
180
- *
181
- * @param table - The database table name (can be a Joi reference)
182
- * @param column - The column name to check (can be a Joi reference)
183
- * @param options - Optional configuration:
184
- * - `caseInsensitive`: Perform case-insensitive comparison (default: false)
185
- * - `filter`: Async function to add additional WHERE clauses to the query
186
- *
187
- * @example
188
- * ```typescript
189
- * const schema = joi.object({
190
- * country_id: joi.number().knex(db).existsInDb('countries', 'id'),
191
- * category: joi.string().knex(db).existsInDb('categories', 'name', {
192
- * caseInsensitive: true
193
- * })
194
- * })
195
- * ```
196
- */
197
- existsInDb(table: string | Reference, column: string | Reference, options?: DbValidationOptions): this;
198
- /**
199
- * Sets a default value if the original value is `undefined`.
200
- *
201
- * @param value - The default value. Can be:
202
- * - A literal value (string, number, object, etc.)
203
- * - A reference to another schema value
204
- * - A function that returns the default value with signature `(parent, helpers) => value`
205
- * - `parent` - A clone of the object containing the value being validated
206
- * - `helpers` - Validation helper functions for custom validation logic
207
- *
208
- * @example
209
- * ```typescript
210
- * const schema = joi.string().default('hello world')
211
- * const schemaWithFunction = joi.number().default((parent, helpers) => parent.someOtherField * 2)
212
- * ```
213
- */
214
- default(value?: DefaultableValue): this;
215
- cast(to: 'map' | 'number' | 'set' | 'string' | 'object'): this;
216
- }
217
- /**
218
- * Schema type for string validation.
219
- *
220
- * @public
221
- */
222
- export interface StringSchema<TSchema = string> extends AnySchema<TSchema> {
223
- /**
224
- * Requires the string value to only contain a-z, A-Z, and 0-9.
225
- */
226
- alphanum(): this;
227
- /**
228
- * Requires the string value to be a valid base64 string; does not check the decoded value.
229
- */
230
- base64(options?: Joi.Base64Options): this;
231
- /**
232
- * Sets the required string case.
233
- */
234
- case(direction: 'upper' | 'lower'): this;
235
- /**
236
- * Requires the number to be a credit card number (Using Luhn Algorithm).
237
- */
238
- creditCard(): this;
239
- /**
240
- * Requires the string value to be a valid data URI string.
241
- */
242
- dataUri(options?: Joi.DataUriOptions): this;
243
- /**
244
- * Requires the string value to be a valid domain.
245
- */
246
- domain(options?: Joi.DomainOptions): this;
247
- /**
248
- * Requires the string value to be a valid email address.
249
- */
250
- email(options?: Joi.EmailOptions): this;
251
- /**
252
- * Requires the string value to be a valid GUID.
253
- */
254
- guid(options?: Joi.GuidOptions): this;
255
- /**
256
- * Requires the string value to be a valid hexadecimal string.
257
- */
258
- hex(options?: Joi.HexOptions): this;
259
- /**
260
- * Requires the string value to be a valid hostname as per RFC1123.
261
- */
262
- hostname(): this;
263
- /**
264
- * Allows the value to match any whitelist of blacklist item in a case insensitive comparison.
265
- */
266
- insensitive(): this;
267
- /**
268
- * Requires the string value to be a valid ip address.
269
- */
270
- ip(options?: Joi.IpOptions): this;
271
- /**
272
- * Requires the string value to be in valid ISO 8601 date format.
273
- */
274
- isoDate(): this;
275
- /**
276
- * Requires the string value to be in valid ISO 8601 duration format.
277
- */
278
- isoDuration(): this;
279
- /**
280
- * Specifies the exact string length required
281
- * @param limit - the required string length. It can also be a reference to another field.
282
- * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
283
- */
284
- length(limit: number | Reference, encoding?: string): this;
285
- /**
286
- * 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.
287
- */
288
- lowercase(): this;
289
- /**
290
- * Specifies the maximum number of string characters.
291
- * @param limit - the maximum number of string characters allowed. It can also be a reference to another field.
292
- * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
293
- */
294
- max(limit: number | Reference, encoding?: string): this;
295
- /**
296
- * Specifies the minimum number string characters.
297
- * @param limit - the minimum number of string characters required. It can also be a reference to another field.
298
- * @param encoding - if specified, the string length is calculated in bytes using the provided encoding.
299
- */
300
- min(limit: number | Reference, encoding?: string): this;
301
- /**
302
- * 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.
303
- * @param [form='NFC'] - The unicode normalization form to use. Valid values: NFC [default], NFD, NFKC, NFKD
304
- */
305
- normalize(form?: 'NFC' | 'NFD' | 'NFKC' | 'NFKD'): this;
306
- /**
307
- * Defines a regular expression rule.
308
- * @param pattern - a regular expression object the string value must match against.
309
- * @param options - optional, can be:
310
- * Name for patterns (useful with multiple patterns). Defaults to 'required'.
311
- * An optional configuration object with the following supported properties:
312
- * name - optional pattern name.
313
- * invert - optional boolean flag. Defaults to false behavior. If specified as true, the provided pattern will be disallowed instead of required.
314
- */
315
- pattern(pattern: RegExp, options?: string | Joi.StringRegexOptions): this;
316
- /**
317
- * Defines a regular expression rule.
318
- * @param pattern - a regular expression object the string value must match against.
319
- * @param options - optional, can be:
320
- * Name for patterns (useful with multiple patterns). Defaults to 'required'.
321
- * An optional configuration object with the following supported properties:
322
- * name - optional pattern name.
323
- * invert - optional boolean flag. Defaults to false behavior. If specified as true, the provided pattern will be disallowed instead of required.
324
- */
325
- regex(pattern: RegExp, options?: string | Joi.StringRegexOptions): this;
326
- /**
327
- * Replace characters matching the given pattern with the specified replacement string where:
328
- * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced.
329
- * @param replacement - the string that will replace the pattern.
330
- */
331
- replace(pattern: RegExp | string, replacement: string): this;
332
- /**
333
- * Requires the string value to only contain a-z, A-Z, 0-9, and underscore _.
334
- */
335
- token(): this;
336
- /**
337
- * 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.
338
- * @param [enabled=true] - optional parameter defaulting to true which allows you to reset the behavior of trim by providing a falsy value.
339
- */
340
- trim(enabled?: any): this;
341
- /**
342
- * Specifies whether the string.max() limit should be used as a truncation.
343
- * @param [enabled=true] - optional parameter defaulting to true which allows you to reset the behavior of truncate by providing a falsy value.
344
- */
345
- truncate(enabled?: boolean): this;
346
- /**
347
- * 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.
348
- */
349
- uppercase(): this;
350
- /**
351
- * Requires the string value to be a valid RFC 3986 URI.
352
- */
353
- uri(options?: Joi.UriOptions): this;
354
- /**
355
- * Requires the string value to be a valid GUID.
356
- */
357
- uuid(options?: Joi.GuidOptions): this;
358
- /**
359
- * Sets a default value if the original value is `undefined`.
360
- *
361
- * @param value - The default value. Can be:
362
- * - A literal string value
363
- * - A reference to another schema value
364
- * - A function that returns the default value with signature `(parent, helpers) => value`
365
- * - `parent` - A clone of the object containing the value being validated
366
- * - `helpers` - Validation helper functions for custom validation logic
367
- */
368
- default(value?: DefaultableValue): this;
369
- /**
370
- * Requires the string value to be a valid fully qualified domain name.
371
- *
372
- * @tip This does not do fully RFC-compliant validation, but a practical approximation.
373
- */
374
- fqdn(): this;
375
- }
376
- /**
377
- * Schema type for binary data validation.
378
- *
379
- * @public
380
- */
381
- export interface BinarySchema<TSchema = Buffer> extends AnySchema<TSchema> {
382
- /**
383
- * Sets the string encoding format if a string input is converted to a buffer.
384
- */
385
- encoding(encoding: string): this;
386
- /**
387
- * Specifies the minimum length of the buffer.
388
- */
389
- min(limit: number | Reference): this;
390
- /**
391
- * Specifies the maximum length of the buffer.
392
- */
393
- max(limit: number | Reference): this;
394
- /**
395
- * Specifies the exact length of the buffer:
396
- */
397
- length(limit: number | Reference): this;
398
- /**
399
- * Sets a default value if the original value is `undefined`.
400
- *
401
- * @param value - The default value. Can be:
402
- * - A literal binary value (Buffer, Uint8Array, etc.)
403
- * - A reference to another schema value
404
- * - A function that returns the default value with signature `(parent, helpers) => value`
405
- * - `parent` - A clone of the object containing the value being validated
406
- * - `helpers` - Validation helper functions for custom validation logic
407
- */
408
- default(value?: DefaultableValue): this;
409
- }
410
- /**
411
- * Schema type for number validation.
412
- *
413
- * @public
414
- */
415
- export interface NumberSchema<TSchema = number> extends AnySchema<TSchema> {
416
- /**
417
- * Specifies that the value must be greater than limit.
418
- * It can also be a reference to another field.
419
- */
420
- greater(limit: number | Reference): this;
421
- /**
422
- * Requires the number to be an integer (no floating point).
423
- */
424
- integer(): this;
425
- /**
426
- * Specifies that the value must be less than limit.
427
- * It can also be a reference to another field.
428
- */
429
- less(limit: number | Reference): this;
430
- /**
431
- * Specifies the maximum value.
432
- * It can also be a reference to another field.
433
- */
434
- max(limit: number | Reference): this;
435
- /**
436
- * Specifies the minimum value.
437
- * It can also be a reference to another field.
438
- */
439
- min(limit: number | Reference): this;
440
- /**
441
- * Specifies that the value must be a multiple of base.
442
- */
443
- multiple(base: number | Reference): this;
444
- /**
445
- * Requires the number to be negative.
446
- */
447
- negative(): this;
448
- /**
449
- * Requires the number to be a TCP port, so between 0 and 65535.
450
- */
451
- port(): this;
452
- /**
453
- * Requires the number to be positive.
454
- */
455
- positive(): this;
456
- /**
457
- * Specifies the maximum number of decimal places where:
458
- * @param limit - the maximum number of decimal places allowed.
459
- */
460
- precision(limit: number): this;
461
- /**
462
- * Requires the number to be negative or positive.
463
- */
464
- sign(sign: 'positive' | 'negative'): this;
465
- /**
466
- * Allows the number to be outside of JavaScript's safety range (Number.MIN_SAFE_INTEGER & Number.MAX_SAFE_INTEGER).
467
- */
468
- unsafe(enabled?: any): this;
469
- /**
470
- * Sets a default value if the original value is `undefined`.
471
- *
472
- * @param value - The default value. Can be:
473
- * - A literal number value
474
- * - A reference to another schema value
475
- * - A function that returns the default value with signature `(parent, helpers) => value`
476
- * - `parent` - A clone of the object containing the value being validated
477
- * - `helpers` - Validation helper functions for custom validation logic
478
- */
479
- default(value?: DefaultableValue): this;
480
- }
481
- /**
482
- * Schema type for boolean validation.
483
- *
484
- * @public
485
- */
486
- export interface BooleanSchema<TSchema = boolean> extends AnySchema<TSchema> {
487
- falsy(...values: Array<string | number | null>): this;
488
- sensitive(enabled?: boolean): this;
489
- truthy(...values: Array<string | number | null>): this;
490
- /**
491
- * Sets a default value if the original value is `undefined`.
492
- *
493
- * @param value - The default value. Can be:
494
- * - A literal boolean value
495
- * - A reference to another schema value
496
- * - A function that returns the default value with signature `(parent, helpers) => value`
497
- * - `parent` - A clone of the object containing the value being validated
498
- * - `helpers` - Validation helper functions for custom validation logic
499
- */
500
- default(value?: DefaultableValue): this;
501
- }
502
- /**
503
- * Schema type for object validation.
504
- *
505
- * @public
506
- */
507
- export interface ObjectSchema<TSchema = any> extends AnySchema<TSchema> {
508
- /**
509
- * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well.
510
- *
511
- * Optional settings must be the last argument.
512
- */
513
- and(...peers: Array<string | Joi.DependencyOptions>): this;
514
- /**
515
- * Appends the allowed object keys. If schema is null, undefined, or {}, no changes will be applied.
516
- */
517
- append(schema?: SchemaMap<TSchema>): this;
518
- append<TSchemaExtended = any, T = TSchemaExtended>(schema?: SchemaMap<T>): ObjectSchema<T>;
519
- /**
520
- * Verifies an assertion where.
521
- */
522
- assert(ref: string | Reference, schema: SchemaLike, message?: string): this;
523
- /**
524
- * Requires the object to be an instance of a given constructor.
525
- *
526
- * @param constructor - the constructor function that the object must be an instance of.
527
- * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name.
528
- */
529
- instance(constructor: Function, name?: string): this;
530
- /**
531
- * Sets or extends the allowed object keys.
532
- */
533
- keys(schema?: SchemaMap<TSchema>): this;
534
- /**
535
- * Specifies the exact number of keys in the object.
536
- */
537
- length(limit: number): this;
538
- /**
539
- * Specifies the maximum number of keys in the object.
540
- */
541
- max(limit: number | Reference): this;
542
- /**
543
- * Specifies the minimum number of keys in the object.
544
- */
545
- min(limit: number | Reference): this;
546
- /**
547
- * Defines a relationship between keys where not all peers can be present at the same time.
548
- *
549
- * Optional settings must be the last argument.
550
- */
551
- nand(...peers: Array<string | Joi.DependencyOptions>): this;
552
- /**
553
- * Defines a relationship between keys where one of the peers is required (and more than one is allowed).
554
- *
555
- * Optional settings must be the last argument.
556
- */
557
- or(...peers: Array<string | Joi.DependencyOptions>): this;
558
- /**
559
- * Defines an exclusive relationship between a set of keys where only one is allowed but none are required.
560
- *
561
- * Optional settings must be the last argument.
562
- */
563
- oxor(...peers: Array<string | Joi.DependencyOptions>): this;
564
- /**
565
- * Specify validation rules for unknown keys matching a pattern.
566
- *
567
- * @param pattern - a pattern that can be either a regular expression or a joi schema that will be tested against the unknown key names
568
- * @param schema - the schema object matching keys must validate against
569
- */
570
- pattern(pattern: RegExp | SchemaLike, schema: SchemaLike, options?: Joi.ObjectPatternOptions): this;
571
- /**
572
- * Requires the object to be a Joi reference.
573
- */
574
- ref(): this;
575
- /**
576
- * Requires the object to be a `RegExp` object.
577
- */
578
- regex(): this;
579
- /**
580
- * Renames a key to another name (deletes the renamed key).
581
- */
582
- rename(from: string | RegExp, to: string, options?: Joi.RenameOptions): this;
583
- /**
584
- * Requires the object to be a Joi schema instance.
585
- */
586
- schema(type?: SchemaLike): this;
587
- /**
588
- * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children).
589
- */
590
- unknown(allow?: boolean): this;
591
- /**
592
- * Requires the presence of other keys whenever the specified key is present.
593
- */
594
- with(key: string, peers: string | string[], options?: Joi.DependencyOptions): this;
595
- /**
596
- * Forbids the presence of other keys whenever the specified is present.
597
- */
598
- without(key: string, peers: string | string[], options?: Joi.DependencyOptions): this;
599
- /**
600
- * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time.
601
- *
602
- * Optional settings must be the last argument.
603
- */
604
- xor(...peers: Array<string | Joi.DependencyOptions>): this;
605
- /**
606
- * Sets a default value if the original value is `undefined`.
607
- *
608
- * @param value - The default value. Can be:
609
- * - A literal object value
610
- * - A reference to another schema value
611
- * - A function that returns the default value with signature `(parent, helpers) => value`
612
- * - `parent` - A clone of the object containing the value being validated
613
- * - `helpers` - Validation helper functions for custom validation logic
614
- *
615
- * When called without any value on an object schema type, a default value will be
616
- * automatically generated based on the default values of the object keys.
617
- */
618
- default(value?: DefaultableValue): this;
619
- }
620
- /**
621
- * Schema type for array validation.
622
- *
623
- * @public
624
- */
625
- export interface ArraySchema<TSchema = any[]> extends AnySchema<TSchema> {
626
- /**
627
- * Verifies that an assertion passes for at least one item in the array, where:
628
- * `schema` - the validation rules required to satisfy the assertion. If the `schema` includes references, they are resolved against
629
- * the array item being tested, not the value of the `ref` target.
630
- */
631
- has(schema: SchemaLike): this;
632
- /**
633
- * Specifies the exact number of items in the array.
634
- */
635
- length(limit: number | Reference): this;
636
- /**
637
- * Specifies the maximum number of items in the array.
638
- */
639
- max(limit: number | Reference): this;
640
- /**
641
- * Specifies the minimum number of items in the array.
642
- */
643
- min(limit: number | Reference): this;
644
- /**
645
- * Allow single values to be checked against rules as if it were provided as an array.
646
- * enabled can be used with a falsy value to go back to the default behavior.
647
- */
648
- single(enabled?: any): this;
649
- /**
650
- * Sorts the array by given order.
651
- */
652
- sort(options?: Joi.ArraySortOptions): this;
653
- /**
654
- * Allow this array to be sparse.
655
- * enabled can be used with a falsy value to go back to the default behavior.
656
- */
657
- sparse(enabled?: any): this;
658
- /**
659
- * Requires the array values to be unique.
660
- * Remember that if you provide a custom comparator function,
661
- * different types can be passed as parameter depending on the rules you set on items.
662
- * Be aware that a deep equality is performed on elements of the array having a type of object,
663
- * a performance penalty is to be expected for this kind of operation.
664
- */
665
- unique(comparator?: string | Joi.ComparatorFunction, options?: Joi.ArrayUniqueOptions): this;
666
- /**
667
- * Sets a default value if the original value is `undefined`.
668
- *
669
- * @param value - The default value. Can be:
670
- * - A literal array value
671
- * - A reference to another schema value
672
- * - A function that returns the default value with signature `(parent, helpers) => value`
673
- * - `parent` - A clone of the object containing the value being validated
674
- * - `helpers` - Validation helper functions for custom validation logic
675
- */
676
- default(value?: DefaultableValue): this;
677
- /**
678
- * List the types allowed for the array values.
679
- * If a given type is .required() then there must be a matching item in the array.
680
- * If a type is .forbidden() then it cannot appear in the array.
681
- * Required items can be added multiple times to signify that multiple items must be found.
682
- * Errors will contain the number of items that didn't match.
683
- * Any unmatched item having a label will be mentioned explicitly.
684
- *
685
- * @param type - a joi schema object to validate each array item against.
686
- */
687
- items(...types: SchemaLikeWithoutArray[]): this;
688
- /**
689
- * Lists the types in sequence order for the array values where:
690
- * @param type - a joi schema object to validate against each array item in sequence order. type can be multiple values passed as individual arguments.
691
- * If a given type is .required() then there must be a matching item with the same index position in the array.
692
- * Errors will contain the number of items that didn't match.
693
- * Any unmatched item having a label will be mentioned explicitly.
694
- */
695
- ordered(...types: SchemaLikeWithoutArray[]): this;
696
- }
697
- /**
698
- * Schema type for date validation.
699
- *
700
- * @public
701
- */
702
- export interface DateSchema<TSchema = Date> extends AnySchema<TSchema> {
703
- /**
704
- * Specifies that the value must be greater than date.
705
- * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
706
- * allowing to explicitly ensure a date is either in the past or in the future.
707
- * It can also be a reference to another field.
708
- */
709
- greater(date: 'now' | Date | number | string | Reference): this;
710
- /**
711
- * Requires the string value to be in valid ISO 8601 date format.
712
- */
713
- iso(): this;
714
- /**
715
- * Specifies that the value must be less than date.
716
- * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
717
- * allowing to explicitly ensure a date is either in the past or in the future.
718
- * It can also be a reference to another field.
719
- */
720
- less(date: 'now' | Date | number | string | Reference): this;
721
- /**
722
- * Specifies the oldest date allowed.
723
- * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
724
- * allowing to explicitly ensure a date is either in the past or in the future.
725
- * It can also be a reference to another field.
726
- */
727
- min(date: 'now' | Date | number | string | Reference): this;
728
- /**
729
- * Specifies the latest date allowed.
730
- * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date,
731
- * allowing to explicitly ensure a date is either in the past or in the future.
732
- * It can also be a reference to another field.
733
- */
734
- max(date: 'now' | Date | number | string | Reference): this;
735
- /**
736
- * Requires the value to be a timestamp interval from Unix Time.
737
- * @param type - the type of timestamp (allowed values are unix or javascript [default])
738
- */
739
- timestamp(type?: 'javascript' | 'unix'): this;
740
- /**
741
- * Sets a default value if the original value is `undefined`.
742
- *
743
- * @param value - The default value. Can be:
744
- * - A literal date value
745
- * - A reference to another schema value
746
- * - A function that returns the default value with signature `(parent, helpers) => value`
747
- * - `parent` - A clone of the object containing the value being validated
748
- * - `helpers` - Validation helper functions for custom validation logic
749
- */
750
- default(value?: DefaultableValue): this;
751
- }
752
- /**
753
- * Schema type for alternatives validation.
754
- *
755
- * @public
756
- */
757
- export interface AlternativesSchema<TSchema = any> extends AnySchema<TSchema> {
758
- /**
759
- * Adds a conditional alternative schema type, either based on another key value, or a schema peeking into the current value.
760
- */
761
- conditional(ref: string | Reference, options: Joi.WhenOptions | Joi.WhenOptions[]): this;
762
- conditional(ref: Schema, options: Joi.WhenSchemaOptions): this;
763
- /**
764
- * Requires the validated value to match a specific set of the provided alternative.try() schemas.
765
- * Cannot be combined with `alternatives.conditional()`.
766
- */
767
- match(mode: 'any' | 'all' | 'one'): this;
768
- /**
769
- * Adds an alternative schema type for attempting to match against the validated value.
770
- */
771
- try(...types: SchemaLikeWithoutArray[]): this;
772
- default(value?: DefaultableValue): this;
773
- }
774
- /**
775
- * Schema type for function validation.
776
- *
777
- * @public
778
- */
779
- export interface FunctionSchema<TSchema = Function> extends ObjectSchema<TSchema> {
780
- /**
781
- * Specifies the arity of the function where:
782
- * @param n - the arity expected.
783
- */
784
- arity(n: number): this;
785
- /**
786
- * Requires the function to be a class.
787
- */
788
- class(): this;
789
- /**
790
- * Specifies the minimal arity of the function where:
791
- * @param n - the minimal arity expected.
792
- */
793
- minArity(n: number): this;
794
- /**
795
- * Specifies the minimal arity of the function where:
796
- * @param n - the minimal arity expected.
797
- */
798
- maxArity(n: number): this;
799
- }
800
- /**
801
- * Schema type for link validation.
802
- *
803
- * @public
804
- */
805
- export interface LinkSchema<TSchema = any> extends AnySchema<TSchema> {
806
- /**
807
- * 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.
808
- * Will throw an exception during validation if the merged types are not compatible.
809
- */
810
- concat(schema: Schema | Joi.Schema): this;
811
- /**
812
- * Initializes the schema after constructions for cases where the schema has to be constructed first and then initialized.
813
- * If `ref` was not passed to the constructor, `link.ref()` must be called prior to usage.
814
- */
815
- ref(ref: string): this;
816
- }
817
- /**
818
- * Schema type for symbol validation.
819
- *
820
- * @public
821
- */
822
- export interface SymbolSchema<TSchema = symbol> extends AnySchema<TSchema> {
823
- map(iterable: Iterable<[string | number | boolean | symbol, symbol]> | {
824
- [key: string]: symbol;
825
- }): this;
826
- }
827
- /**
828
- * A union type that includes all schema types.
829
- */
830
- export type Schema<P = any> = AnySchema<P> | ArraySchema<P> | AlternativesSchema<P> | BinarySchema<P> | BooleanSchema<P> | DateSchema<P> | FunctionSchema<P> | NumberSchema<P> | ObjectSchema<P> | StringSchema<P> | LinkSchema<P> | SymbolSchema<P> | BigIntSchema<P> | DatetimeSchema<P> | PhoneSchema<P>;
831
- export type ObjectPropertiesSchema<T = any> = true extends Joi.IsNonPrimitiveSubsetUnion<Exclude<T, undefined | null>> ? AlternativesSchema : T extends Joi.NullableType<string> ? StringSchema : T extends Joi.NullableType<number> ? NumberSchema : T extends Joi.NullableType<bigint> ? BigIntSchema : T extends Joi.NullableType<boolean> ? BooleanSchema : T extends Joi.NullableType<Date> ? DateSchema : T extends Joi.NullableType<Buffer> ? BinarySchema : T extends Joi.NullableType<Array<any>> ? ArraySchema : T extends DateTime ? DatetimeSchema : T extends Joi.NullableType<object> ? StrictSchemaMap<T> | ObjectSchema<T> : never;
832
- export type PartialSchemaMap<TSchema = any> = {
833
- [key in keyof TSchema]?: SchemaLike | SchemaLike[];
834
- };
835
- export type StrictSchemaMap<TSchema = any> = {
836
- [key in keyof TSchema]-?: ObjectPropertiesSchema<TSchema[key]>;
837
- };
838
- export type SchemaMap<TSchema = any, IsStrict = false> = IsStrict extends true ? StrictSchemaMap<TSchema> : PartialSchemaMap<TSchema>;
839
- export type SchemaLikeWithoutArray = string | number | boolean | null | Schema | SchemaMap;
840
- export type SchemaLike = SchemaLikeWithoutArray | object;