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