universal-validator 2.0.0

Comprehensive data validation library for API, database, and form contexts
Documentation
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
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
//! Universal Data Validator
//!
//! A comprehensive data validation library for Rust that works across API, database, and form contexts.
//!
//! # Features
//!
//! - **Rich Validator Types**: String, integer, float, bool, email, URL, UUID, date,
//!   datetime, numeric, not-empty, enum, one-of, array (`Vec`) and object (`Map`)
//! - **Schema-Based Validation**: Define complex, nested data structures
//! - **Custom Validators**: Add your own validation logic
//! - **Nullable & Optional**: Fine-grained control over missing and `null` values
//! - **Strict Mode**: Reject unknown fields
//! - **Clear Error Messages**: Detailed error reporting with full field paths
//!
//! # Examples
//!
//! ```
//! use serde_json::json;
//! use universal_validator::{Schema, validators};
//!
//! let schema = Schema::new()
//!     .field("email", validators::email())
//!     .field("age", validators::int().min(0).max(120))
//!     .field("username", validators::string().min(3).max(20));
//!
//! let data = json!({
//!     "email": "user@example.com",
//!     "age": 25,
//!     "username": "john_doe"
//! });
//!
//! let result = schema.validate(&data);
//! assert!(result.is_valid());
//! ```

use regex::Regex;
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;
use std::sync::OnceLock;

/// Canonical error codes returned by validators.
pub mod codes {
    pub const REQUIRED: &str = "required";
    pub const UNKNOWN_FIELD: &str = "unknown_field";
    pub const TYPE: &str = "type";
    pub const MIN_LENGTH: &str = "min_length";
    pub const MAX_LENGTH: &str = "max_length";
    pub const MIN_VALUE: &str = "min_value";
    pub const MAX_VALUE: &str = "max_value";
    pub const PATTERN: &str = "pattern";
    pub const CHOICES: &str = "choices";
    pub const EMAIL: &str = "email";
    pub const URL: &str = "url";
    pub const CUSTOM: &str = "custom";
    pub const UUID: &str = "uuid";
    pub const DATE: &str = "date";
    pub const DATETIME: &str = "datetime";
    pub const NUMERIC: &str = "numeric";
    pub const NOT_EMPTY: &str = "not_empty";
    pub const ENUM: &str = "enum";
    pub const ONE_OF: &str = "one_of";
}

/// A single validation error.
#[derive(Debug, Clone)]
pub struct ValidationError {
    pub field: String,
    pub message: String,
    pub code: String,
    pub value: Option<Value>,
}

impl ValidationError {
    /// Create a new validation error.
    pub fn new(field: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            message: message.into(),
            code: String::new(),
            value: None,
        }
    }

    /// Set the machine-readable error code.
    pub fn with_code(mut self, code: impl Into<String>) -> Self {
        self.code = code.into();
        self
    }

    /// Attach the value that caused the error.
    ///
    /// Accepts either a [`Value`] or an `Option<Value>`; passing `None`
    /// (e.g. from a `sensitive` validator) leaves the value unset.
    pub fn with_value(mut self, value: impl Into<Option<Value>>) -> Self {
        self.value = value.into();
        self
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.field, self.message)
    }
}

impl std::error::Error for ValidationError {}

/// An aggregate of [`ValidationError`]s returned by [`Schema::try_validate`].
///
/// `Display` renders one `field: message` per line.
#[derive(Debug, Clone)]
pub struct ValidationErrors(pub Vec<ValidationError>);

impl fmt::Display for ValidationErrors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, error) in self.0.iter().enumerate() {
            if i > 0 {
                writeln!(f)?;
            }
            write!(f, "{error}")?;
        }
        Ok(())
    }
}

impl std::error::Error for ValidationErrors {}

/// The result of validating a value or schema.
#[derive(Debug, Clone, Default)]
pub struct ValidationResult {
    errors: Vec<ValidationError>,
}

impl ValidationResult {
    /// Create a new, empty validation result.
    pub fn new() -> Self {
        Self { errors: Vec::new() }
    }

    /// Whether validation succeeded.
    pub fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }

    /// The list of validation errors.
    pub fn errors(&self) -> &[ValidationError] {
        &self.errors
    }

    /// Add an error to the result.
    pub fn add_error(&mut self, error: ValidationError) {
        self.errors.push(error);
    }

    /// Merge another validation result into this one.
    pub fn merge(&mut self, other: ValidationResult) {
        self.errors.extend(other.errors);
    }

    /// Convert the result into `Ok(())` when valid, or a
    /// [`ValidationErrors`] aggregate on failure.
    pub fn into_result(self) -> Result<(), ValidationErrors> {
        if self.errors.is_empty() {
            Ok(())
        } else {
            Err(ValidationErrors(self.errors))
        }
    }
}

/// The trait implemented by all validators.
///
/// Validators operate on [`serde_json::Value`] so the same rules can be reused
/// for JSON APIs, configuration files, and form data.
pub trait Validator: Send + Sync {
    /// Validate `value` at the given `field` path.
    fn validate(&self, value: &Value, field: &str) -> ValidationResult;

    /// Whether the field is required.
    fn is_required(&self) -> bool;

    /// Whether the field may be explicitly `null`.
    fn is_nullable(&self) -> bool;

    /// Set fail-fast mode for this validator and its children.
    fn set_fail_fast(&mut self, _fail_fast: bool) {}
}

/// Allow boxed validators to be used anywhere a [`Validator`] is expected
/// (e.g. when building schemas dynamically).
impl Validator for Box<dyn Validator> {
    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        (**self).validate(value, field)
    }

    fn is_required(&self) -> bool {
        (**self).is_required()
    }

    fn is_nullable(&self) -> bool {
        (**self).is_nullable()
    }

    fn set_fail_fast(&mut self, fail_fast: bool) {
        (**self).set_fail_fast(fail_fast);
    }
}

/// Maximum length (in Unicode scalar values) of a string that a `pattern`
/// check will run against. Inputs longer than this skip the match and produce
/// the normal pattern error.
///
/// Rust's `regex` crate guarantees linear-time matching, so this cap exists
/// for cross-language spec parity with backtracking engines (Python `re`,
/// JS `RegExp`).
pub const MAX_PATTERN_INPUT_LENGTH: usize = 10_000;

/// A user-supplied validation function. Returning `Some(message)` rejects the
/// value with that message (code `custom`).
type CustomValidator = Box<dyn Fn(&Value) -> Option<String> + Send + Sync>;

struct Base {
    required: bool,
    nullable: bool,
    fail_fast: bool,
    /// When true, the offending value is redacted from error messages
    /// (rendered as `***`) and `ValidationError::value` is left `None`.
    sensitive: bool,
    custom_validators: Vec<CustomValidator>,
}

impl Base {
    fn new() -> Self {
        Self {
            required: true,
            nullable: false,
            fail_fast: false,
            sensitive: false,
            custom_validators: Vec::new(),
        }
    }

    fn is_required(&self) -> bool {
        self.required
    }

    fn is_nullable(&self) -> bool {
        self.nullable
    }

    /// Render a string value for an error message, or `***` when sensitive.
    fn display<'a>(&self, s: &'a str) -> &'a str {
        if self.sensitive {
            "***"
        } else {
            s
        }
    }

    /// Render an arbitrary JSON value for an error message, or `***` when
    /// sensitive.
    fn display_json(&self, value: &Value) -> String {
        if self.sensitive {
            "***".to_string()
        } else {
            serde_json::to_string(value).unwrap_or_else(|_| value.to_string())
        }
    }

    /// The value to attach to an error, or `None` when sensitive.
    fn err_value(&self, value: &Value) -> Option<Value> {
        if self.sensitive {
            None
        } else {
            Some(value.clone())
        }
    }

    fn handle_null(&self, field: &str, fail_fast: bool) -> ValidationResult {
        let mut result = ValidationResult::new();
        if self.required && !self.nullable {
            result.add_error(
                ValidationError::new(field, "Field is required").with_code(codes::REQUIRED),
            );
            if fail_fast {
                return result;
            }
        }
        result
    }

    fn run_custom(
        &self,
        value: &Value,
        field: &str,
        result: &mut ValidationResult,
        fail_fast: bool,
    ) {
        for validator in &self.custom_validators {
            if let Some(message) = validator(value) {
                result.add_error(
                    ValidationError::new(field, message)
                        .with_code(codes::CUSTOM)
                        .with_value(self.err_value(value)),
                );
                if fail_fast {
                    break;
                }
            }
        }
    }
}

macro_rules! base_methods {
    ($type:ty) => {
        impl $type {
            /// Make the field optional (equivalent to `required = false`).
            pub fn optional(mut self) -> Self {
                self.base.required = false;
                self
            }

            /// Allow the field to be explicitly `null`.
            pub fn nullable(mut self) -> Self {
                self.base.nullable = true;
                self
            }

            /// Mark the field as required.
            pub fn required(mut self) -> Self {
                self.base.required = true;
                self
            }

            /// Mark the field as sensitive (e.g. passwords, tokens).
            ///
            /// When enabled, every error this validator produces redacts the
            /// offending value: message interpolations render as `***` and
            /// [`ValidationError::value`] is `None`, so errors can be logged
            /// safely. The flag is per-validator and is NOT inherited by
            /// nested validators.
            pub fn sensitive(mut self, sensitive: bool) -> Self {
                self.base.sensitive = sensitive;
                self
            }

            /// Add a custom validation function.
            ///
            /// The function receives the value and should return `Some(message)`
            /// when invalid. Custom validators run after type and constraint checks.
            pub fn custom<F>(mut self, f: F) -> Self
            where
                F: Fn(&Value) -> Option<String> + Send + Sync + 'static,
            {
                self.base.custom_validators.push(Box::new(f));
                self
            }

            /// Stop at the first validation error.
            ///
            /// When enabled, validation returns a result containing exactly one
            /// error. The flag is propagated to nested validators.
            pub fn fail_fast(mut self, fail_fast: bool) -> Self {
                self.set_fail_fast(fail_fast);
                self
            }
        }
    };
}

/// Return the canonical JSON kind name for a value.
///
/// Numbers are `"integer"` when integral (`i64`, `u64`, or integral `f64`)
/// and `"number"` otherwise.
fn kind_name(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(n) => {
            if n.is_i64() || n.is_u64() {
                "integer"
            } else if let Some(f) = n.as_f64() {
                if f.fract() == 0.0 && f.is_finite() {
                    "integer"
                } else {
                    "number"
                }
            } else {
                "number"
            }
        }
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

// Email and URL patterns are compiled exactly once on first use.
static EMAIL_RE: OnceLock<Regex> = OnceLock::new();
static URL_RE: OnceLock<Regex> = OnceLock::new();

fn email_regex() -> &'static Regex {
    EMAIL_RE
        .get_or_init(|| Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap())
}

fn url_regex() -> &'static Regex {
    URL_RE.get_or_init(|| Regex::new(r"^https?://[^\s/$.?#].[^\s]*$").unwrap())
}

// Fixed-format patterns (uuid/date/datetime/numeric) are compiled exactly
// once on first use.
static UUID_RE: OnceLock<Regex> = OnceLock::new();
static DATE_RE: OnceLock<Regex> = OnceLock::new();
static DATETIME_RE: OnceLock<Regex> = OnceLock::new();
static NUMERIC_RE: OnceLock<Regex> = OnceLock::new();

fn uuid_regex() -> &'static Regex {
    UUID_RE.get_or_init(|| {
        Regex::new(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
            .unwrap()
    })
}

fn date_regex() -> &'static Regex {
    DATE_RE.get_or_init(|| Regex::new(r"^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$").unwrap())
}

fn datetime_regex() -> &'static Regex {
    DATETIME_RE.get_or_init(|| {
        Regex::new(
            r"^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T([01]\d|2[0-3]):[0-5]\d:[0-5]\d(\.\d+)?(Z|[+-]([01]\d|2[0-3]):[0-5]\d)$",
        )
        .unwrap()
    })
}

fn numeric_regex() -> &'static Regex {
    NUMERIC_RE.get_or_init(|| Regex::new(r"^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?$").unwrap())
}

/// Validator for JSON strings.
pub struct StringValidator {
    base: Base,
    min_length: Option<usize>,
    max_length: Option<usize>,
    /// Raw pattern source (for error messages) plus the anchored compiled regex.
    pattern: Option<(String, Regex)>,
    choices: Option<Vec<String>>,
}

/// Anchor a pattern so it must match the entire string (full-match semantics).
fn anchor_pattern(source: &str) -> Result<Regex, regex::Error> {
    Regex::new(&format!("^(?:{source})$"))
}

impl StringValidator {
    /// Create a new string validator.
    pub fn new() -> Self {
        Self {
            base: Base::new(),
            min_length: None,
            max_length: None,
            pattern: None,
            choices: None,
        }
    }

    /// Set the minimum length (measured in Unicode scalars).
    pub fn min(mut self, min: usize) -> Self {
        self.min_length = Some(min);
        self
    }

    /// Set the maximum length (measured in Unicode scalars).
    pub fn max(mut self, max: usize) -> Self {
        self.max_length = Some(max);
        self
    }

    /// Set a pre-compiled regex pattern. The pattern is anchored so it must
    /// match the entire string (full-match semantics).
    ///
    /// For a fallible builder, see [`StringValidator::try_pattern`].
    pub fn pattern(mut self, pattern: Regex) -> Self {
        let source = pattern.as_str().to_string();
        let anchored = anchor_pattern(&source).unwrap_or(pattern);
        self.pattern = Some((source, anchored));
        self
    }

    /// Compile a regex pattern. The pattern is anchored so it must match the
    /// entire string (full-match semantics). Returns an error if the pattern
    /// is invalid.
    pub fn try_pattern(mut self, pattern: &str) -> Result<Self, regex::Error> {
        let anchored = anchor_pattern(pattern)?;
        self.pattern = Some((pattern.to_string(), anchored));
        Ok(self)
    }

    /// Restrict the value to a set of allowed strings.
    pub fn choices(mut self, choices: Vec<String>) -> Self {
        self.choices = Some(choices);
        self
    }
}

base_methods!(StringValidator);

impl Validator for StringValidator {
    fn set_fail_fast(&mut self, fail_fast: bool) {
        self.base.fail_fast = fail_fast;
    }

    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        let fail_fast = self.base.fail_fast;
        if value.is_null() {
            return self.base.handle_null(field, fail_fast);
        }

        let mut result = ValidationResult::new();

        let Some(s) = value.as_str() else {
            result.add_error(
                ValidationError::new(field, format!("Expected string, got {}", kind_name(value)))
                    .with_code(codes::TYPE)
                    .with_value(self.base.err_value(value)),
            );
            return result;
        };

        let len = s.chars().count();

        if let Some(min) = self.min_length {
            if len < min {
                result.add_error(
                    ValidationError::new(
                        field,
                        format!("String length must be at least {min}, got {len}"),
                    )
                    .with_code(codes::MIN_LENGTH)
                    .with_value(self.base.err_value(value)),
                );
                if fail_fast {
                    return result;
                }
            }
        }

        if let Some(max) = self.max_length {
            if len > max {
                result.add_error(
                    ValidationError::new(
                        field,
                        format!("String length must be at most {max}, got {len}"),
                    )
                    .with_code(codes::MAX_LENGTH)
                    .with_value(self.base.err_value(value)),
                );
                if fail_fast {
                    return result;
                }
            }
        }

        if let Some((source, pattern)) = &self.pattern {
            // `regex` is linear-time; the cap exists for spec parity (see
            // MAX_PATTERN_INPUT_LENGTH).
            if len > MAX_PATTERN_INPUT_LENGTH || !pattern.is_match(s) {
                result.add_error(
                    ValidationError::new(field, format!("String does not match pattern {source}"))
                        .with_code(codes::PATTERN)
                        .with_value(self.base.err_value(value)),
                );
                if fail_fast {
                    return result;
                }
            }
        }

        if let Some(choices) = &self.choices {
            if !choices.iter().any(|c| c == s) {
                result.add_error(
                    ValidationError::new(
                        field,
                        format!(
                            "Value must be one of {}, got '{}'",
                            choices.join(", "),
                            self.base.display(s)
                        ),
                    )
                    .with_code(codes::CHOICES)
                    .with_value(self.base.err_value(value)),
                );
                if fail_fast {
                    return result;
                }
            }
        }

        self.base.run_custom(value, field, &mut result, fail_fast);
        result
    }

    fn is_required(&self) -> bool {
        self.base.is_required()
    }

    fn is_nullable(&self) -> bool {
        self.base.is_nullable()
    }
}

/// Validator for JSON integers.
pub struct IntValidator {
    base: Base,
    min_value: Option<i64>,
    max_value: Option<i64>,
}

impl IntValidator {
    /// Create a new integer validator.
    pub fn new() -> Self {
        Self {
            base: Base::new(),
            min_value: None,
            max_value: None,
        }
    }

    /// Set the minimum allowed value.
    pub fn min(mut self, min: i64) -> Self {
        self.min_value = Some(min);
        self
    }

    /// Set the maximum allowed value.
    pub fn max(mut self, max: i64) -> Self {
        self.max_value = Some(max);
        self
    }
}

base_methods!(IntValidator);

impl Validator for IntValidator {
    fn set_fail_fast(&mut self, fail_fast: bool) {
        self.base.fail_fast = fail_fast;
    }

    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        let fail_fast = self.base.fail_fast;
        if value.is_null() {
            return self.base.handle_null(field, fail_fast);
        }

        let mut result = ValidationResult::new();

        let parsed = value
            .as_i64()
            .or_else(|| value.as_u64().and_then(|u| i64::try_from(u).ok()))
            .or_else(|| {
                value.as_f64().and_then(|f| {
                    if f.fract() == 0.0
                        && f.is_finite()
                        && f >= i64::MIN as f64
                        && f <= i64::MAX as f64
                    {
                        Some(f as i64)
                    } else {
                        None
                    }
                })
            });

        let Some(num) = parsed else {
            result.add_error(
                ValidationError::new(field, format!("Expected integer, got {}", kind_name(value)))
                    .with_code(codes::TYPE)
                    .with_value(self.base.err_value(value)),
            );
            return result;
        };

        if let Some(min) = self.min_value {
            if num < min {
                result.add_error(
                    ValidationError::new(field, format!("Value must be at least {min}, got {num}"))
                        .with_code(codes::MIN_VALUE)
                        .with_value(self.base.err_value(value)),
                );
                if fail_fast {
                    return result;
                }
            }
        }

        if let Some(max) = self.max_value {
            if num > max {
                result.add_error(
                    ValidationError::new(field, format!("Value must be at most {max}, got {num}"))
                        .with_code(codes::MAX_VALUE)
                        .with_value(self.base.err_value(value)),
                );
                if fail_fast {
                    return result;
                }
            }
        }

        self.base.run_custom(value, field, &mut result, fail_fast);
        result
    }

    fn is_required(&self) -> bool {
        self.base.is_required()
    }

    fn is_nullable(&self) -> bool {
        self.base.is_nullable()
    }
}

/// Validator for JSON numbers (integers and floats).
pub struct FloatValidator {
    base: Base,
    min_value: Option<f64>,
    max_value: Option<f64>,
}

impl FloatValidator {
    /// Create a new float/number validator.
    pub fn new() -> Self {
        Self {
            base: Base::new(),
            min_value: None,
            max_value: None,
        }
    }

    /// Set the minimum allowed value.
    pub fn min(mut self, min: f64) -> Self {
        self.min_value = Some(min);
        self
    }

    /// Set the maximum allowed value.
    pub fn max(mut self, max: f64) -> Self {
        self.max_value = Some(max);
        self
    }
}

base_methods!(FloatValidator);

impl Validator for FloatValidator {
    fn set_fail_fast(&mut self, fail_fast: bool) {
        self.base.fail_fast = fail_fast;
    }

    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        let fail_fast = self.base.fail_fast;
        if value.is_null() {
            return self.base.handle_null(field, fail_fast);
        }

        let mut result = ValidationResult::new();

        let Some(num) = value.as_f64() else {
            result.add_error(
                ValidationError::new(field, format!("Expected number, got {}", kind_name(value)))
                    .with_code(codes::TYPE)
                    .with_value(self.base.err_value(value)),
            );
            return result;
        };

        if let Some(min) = self.min_value {
            if num < min {
                result.add_error(
                    ValidationError::new(field, format!("Value must be at least {min}, got {num}"))
                        .with_code(codes::MIN_VALUE)
                        .with_value(self.base.err_value(value)),
                );
                if fail_fast {
                    return result;
                }
            }
        }

        if let Some(max) = self.max_value {
            if num > max {
                result.add_error(
                    ValidationError::new(field, format!("Value must be at most {max}, got {num}"))
                        .with_code(codes::MAX_VALUE)
                        .with_value(self.base.err_value(value)),
                );
                if fail_fast {
                    return result;
                }
            }
        }

        self.base.run_custom(value, field, &mut result, fail_fast);
        result
    }

    fn is_required(&self) -> bool {
        self.base.is_required()
    }

    fn is_nullable(&self) -> bool {
        self.base.is_nullable()
    }
}

/// Validator for JSON booleans.
pub struct BoolValidator {
    base: Base,
}

impl BoolValidator {
    /// Create a new boolean validator.
    pub fn new() -> Self {
        Self { base: Base::new() }
    }
}

base_methods!(BoolValidator);

impl Validator for BoolValidator {
    fn set_fail_fast(&mut self, fail_fast: bool) {
        self.base.fail_fast = fail_fast;
    }

    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        let fail_fast = self.base.fail_fast;
        if value.is_null() {
            return self.base.handle_null(field, fail_fast);
        }

        let mut result = ValidationResult::new();

        if !value.is_boolean() {
            result.add_error(
                ValidationError::new(field, format!("Expected boolean, got {}", kind_name(value)))
                    .with_code(codes::TYPE)
                    .with_value(self.base.err_value(value)),
            );
            return result;
        }

        self.base.run_custom(value, field, &mut result, fail_fast);
        result
    }

    fn is_required(&self) -> bool {
        self.base.is_required()
    }

    fn is_nullable(&self) -> bool {
        self.base.is_nullable()
    }
}

/// Validator for email addresses.
pub struct EmailValidator {
    base: Base,
}

impl EmailValidator {
    /// Create a new email validator.
    pub fn new() -> Self {
        Self { base: Base::new() }
    }
}

base_methods!(EmailValidator);

impl Validator for EmailValidator {
    fn set_fail_fast(&mut self, fail_fast: bool) {
        self.base.fail_fast = fail_fast;
    }

    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        let fail_fast = self.base.fail_fast;
        if value.is_null() {
            return self.base.handle_null(field, fail_fast);
        }

        let mut result = ValidationResult::new();

        let Some(s) = value.as_str() else {
            result.add_error(
                ValidationError::new(field, format!("Expected string, got {}", kind_name(value)))
                    .with_code(codes::TYPE)
                    .with_value(self.base.err_value(value)),
            );
            return result;
        };

        // `regex` is linear-time; the cap exists for spec parity.
        if s.chars().count() > MAX_PATTERN_INPUT_LENGTH || !email_regex().is_match(s) {
            result.add_error(
                ValidationError::new(
                    field,
                    format!("Invalid email address: {}", self.base.display(s)),
                )
                .with_code(codes::EMAIL)
                .with_value(self.base.err_value(value)),
            );
            if fail_fast {
                return result;
            }
        }

        self.base.run_custom(value, field, &mut result, fail_fast);
        result
    }

    fn is_required(&self) -> bool {
        self.base.is_required()
    }

    fn is_nullable(&self) -> bool {
        self.base.is_nullable()
    }
}

/// Validator for URLs.
pub struct UrlValidator {
    base: Base,
}

impl UrlValidator {
    /// Create a new URL validator.
    pub fn new() -> Self {
        Self { base: Base::new() }
    }
}

base_methods!(UrlValidator);

impl Validator for UrlValidator {
    fn set_fail_fast(&mut self, fail_fast: bool) {
        self.base.fail_fast = fail_fast;
    }

    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        let fail_fast = self.base.fail_fast;
        if value.is_null() {
            return self.base.handle_null(field, fail_fast);
        }

        let mut result = ValidationResult::new();

        let Some(s) = value.as_str() else {
            result.add_error(
                ValidationError::new(field, format!("Expected string, got {}", kind_name(value)))
                    .with_code(codes::TYPE)
                    .with_value(self.base.err_value(value)),
            );
            return result;
        };

        // `regex` is linear-time; the cap exists for spec parity.
        if s.chars().count() > MAX_PATTERN_INPUT_LENGTH || !url_regex().is_match(s) {
            result.add_error(
                ValidationError::new(field, format!("Invalid URL: {}", self.base.display(s)))
                    .with_code(codes::URL)
                    .with_value(self.base.err_value(value)),
            );
            if fail_fast {
                return result;
            }
        }

        self.base.run_custom(value, field, &mut result, fail_fast);
        result
    }

    fn is_required(&self) -> bool {
        self.base.is_required()
    }

    fn is_nullable(&self) -> bool {
        self.base.is_nullable()
    }
}

/// Generate a string validator that checks a fixed regex and reports
/// mismatches with a dedicated error code and message.
macro_rules! fixed_pattern_validator {
    ($type:ident, $doc:literal, $regex_fn:ident, $code:expr, $msg:literal) => {
        #[doc = $doc]
        pub struct $type {
            base: Base,
        }

        impl $type {
            /// Create a new validator.
            pub fn new() -> Self {
                Self { base: Base::new() }
            }
        }

        base_methods!($type);

        impl Default for $type {
            fn default() -> Self {
                Self::new()
            }
        }

        impl Validator for $type {
            fn set_fail_fast(&mut self, fail_fast: bool) {
                self.base.fail_fast = fail_fast;
            }

            fn validate(&self, value: &Value, field: &str) -> ValidationResult {
                let fail_fast = self.base.fail_fast;
                if value.is_null() {
                    return self.base.handle_null(field, fail_fast);
                }

                let mut result = ValidationResult::new();

                let Some(s) = value.as_str() else {
                    result.add_error(
                        ValidationError::new(
                            field,
                            format!("Expected string, got {}", kind_name(value)),
                        )
                        .with_code(codes::TYPE)
                        .with_value(self.base.err_value(value)),
                    );
                    return result;
                };

                // `regex` is linear-time; the cap exists for spec parity.
                if s.chars().count() > MAX_PATTERN_INPUT_LENGTH || !$regex_fn().is_match(s) {
                    result.add_error(
                        ValidationError::new(field, format!($msg, self.base.display(s)))
                            .with_code($code)
                            .with_value(self.base.err_value(value)),
                    );
                    if fail_fast {
                        return result;
                    }
                }

                self.base.run_custom(value, field, &mut result, fail_fast);
                result
            }

            fn is_required(&self) -> bool {
                self.base.is_required()
            }

            fn is_nullable(&self) -> bool {
                self.base.is_nullable()
            }
        }
    };
}

fixed_pattern_validator!(
    UuidValidator,
    "Validator for UUID strings.",
    uuid_regex,
    codes::UUID,
    "Invalid UUID: {}"
);

fixed_pattern_validator!(
    DateValidator,
    "Validator for `YYYY-MM-DD` date strings.",
    date_regex,
    codes::DATE,
    "Invalid date: {}"
);

fixed_pattern_validator!(
    DatetimeValidator,
    "Validator for ISO-8601 style datetime strings.",
    datetime_regex,
    codes::DATETIME,
    "Invalid datetime: {}"
);

fixed_pattern_validator!(
    NumericValidator,
    "Validator for strings that contain a valid JSON-style number.",
    numeric_regex,
    codes::NUMERIC,
    "Expected numeric string, got {}"
);

/// Validator that requires a non-empty string, array, or object.
pub struct NotEmptyValidator {
    base: Base,
}

impl NotEmptyValidator {
    /// Create a new not-empty validator.
    pub fn new() -> Self {
        Self { base: Base::new() }
    }
}

base_methods!(NotEmptyValidator);

impl Validator for NotEmptyValidator {
    fn set_fail_fast(&mut self, fail_fast: bool) {
        self.base.fail_fast = fail_fast;
    }

    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        let fail_fast = self.base.fail_fast;
        if value.is_null() {
            return self.base.handle_null(field, fail_fast);
        }

        let mut result = ValidationResult::new();

        let is_empty = match value {
            Value::String(s) => s.is_empty(),
            Value::Array(arr) => arr.is_empty(),
            Value::Object(map) => map.is_empty(),
            _ => {
                result.add_error(
                    ValidationError::new(
                        field,
                        format!(
                            "Expected string, array, or object, got {}",
                            kind_name(value)
                        ),
                    )
                    .with_code(codes::TYPE)
                    .with_value(self.base.err_value(value)),
                );
                return result;
            }
        };

        if is_empty {
            result.add_error(
                ValidationError::new(field, "Value must not be empty")
                    .with_code(codes::NOT_EMPTY)
                    .with_value(self.base.err_value(value)),
            );
            if fail_fast {
                return result;
            }
        }

        self.base.run_custom(value, field, &mut result, fail_fast);
        result
    }

    fn is_required(&self) -> bool {
        self.base.is_required()
    }

    fn is_nullable(&self) -> bool {
        self.base.is_nullable()
    }
}

/// Validator that checks membership in a fixed set of JSON values
/// (deep-equality semantics).
pub struct EnumValidator {
    base: Base,
    values: Vec<Value>,
}

impl EnumValidator {
    /// Create a new enum validator over the given allowed values.
    pub fn new(values: Vec<Value>) -> Self {
        Self {
            base: Base::new(),
            values,
        }
    }
}

base_methods!(EnumValidator);

impl Validator for EnumValidator {
    fn set_fail_fast(&mut self, fail_fast: bool) {
        self.base.fail_fast = fail_fast;
    }

    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        let fail_fast = self.base.fail_fast;
        if value.is_null() {
            return self.base.handle_null(field, fail_fast);
        }

        let mut result = ValidationResult::new();

        if !self.values.iter().any(|v| v == value) {
            let allowed = self
                .values
                .iter()
                .map(|v| serde_json::to_string(v).unwrap_or_else(|_| v.to_string()))
                .collect::<Vec<_>>()
                .join(", ");
            let got = self.base.display_json(value);
            result.add_error(
                ValidationError::new(field, format!("Value must be one of {allowed}, got {got}"))
                    .with_code(codes::ENUM)
                    .with_value(self.base.err_value(value)),
            );
            if fail_fast {
                return result;
            }
        }

        self.base.run_custom(value, field, &mut result, fail_fast);
        result
    }

    fn is_required(&self) -> bool {
        self.base.is_required()
    }

    fn is_nullable(&self) -> bool {
        self.base.is_nullable()
    }
}

/// Validator that accepts a value when at least one branch validator
/// produces zero errors at the same field path.
pub struct OneOfValidator {
    base: Base,
    branches: Vec<Box<dyn Validator>>,
}

impl OneOfValidator {
    /// Create a new one-of validator over the given branch validators.
    pub fn new(branches: Vec<Box<dyn Validator>>) -> Self {
        Self {
            base: Base::new(),
            branches,
        }
    }
}

base_methods!(OneOfValidator);

impl Validator for OneOfValidator {
    fn set_fail_fast(&mut self, fail_fast: bool) {
        self.base.fail_fast = fail_fast;
        for branch in &mut self.branches {
            branch.set_fail_fast(fail_fast);
        }
    }

    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        let fail_fast = self.base.fail_fast;
        if value.is_null() {
            return self.base.handle_null(field, fail_fast);
        }

        let mut result = ValidationResult::new();

        let any_match = self
            .branches
            .iter()
            .any(|branch| branch.validate(value, field).is_valid());

        if !any_match {
            result.add_error(
                ValidationError::new(field, "Value does not match any allowed schema")
                    .with_code(codes::ONE_OF)
                    .with_value(self.base.err_value(value)),
            );
            if fail_fast {
                return result;
            }
        }

        self.base.run_custom(value, field, &mut result, fail_fast);
        result
    }

    fn is_required(&self) -> bool {
        self.base.is_required()
    }

    fn is_nullable(&self) -> bool {
        self.base.is_nullable()
    }
}

/// Validator for JSON arrays.
pub struct VecValidator {
    base: Base,
    item_validator: Option<Box<dyn Validator>>,
    min_length: Option<usize>,
    max_length: Option<usize>,
}

impl VecValidator {
    /// Create a new array validator.
    pub fn new() -> Self {
        Self {
            base: Base::new(),
            item_validator: None,
            min_length: None,
            max_length: None,
        }
    }

    /// Set a validator for each array item.
    pub fn item(mut self, mut validator: impl Validator + 'static) -> Self {
        validator.set_fail_fast(self.base.fail_fast);
        self.item_validator = Some(Box::new(validator));
        self
    }

    /// Set the minimum array length.
    pub fn min(mut self, min: usize) -> Self {
        self.min_length = Some(min);
        self
    }

    /// Set the maximum array length.
    pub fn max(mut self, max: usize) -> Self {
        self.max_length = Some(max);
        self
    }
}

base_methods!(VecValidator);

impl Validator for VecValidator {
    fn set_fail_fast(&mut self, fail_fast: bool) {
        self.base.fail_fast = fail_fast;
        if let Some(item_validator) = self.item_validator.as_mut() {
            item_validator.set_fail_fast(fail_fast);
        }
    }

    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        let fail_fast = self.base.fail_fast;
        if value.is_null() {
            return self.base.handle_null(field, fail_fast);
        }

        let mut result = ValidationResult::new();

        let Some(arr) = value.as_array() else {
            result.add_error(
                ValidationError::new(field, format!("Expected array, got {}", kind_name(value)))
                    .with_code(codes::TYPE)
                    .with_value(self.base.err_value(value)),
            );
            return result;
        };

        if let Some(min) = self.min_length {
            if arr.len() < min {
                result.add_error(
                    ValidationError::new(
                        field,
                        format!("Array length must be at least {min}, got {}", arr.len()),
                    )
                    .with_code(codes::MIN_LENGTH)
                    .with_value(self.base.err_value(value)),
                );
                if fail_fast {
                    return result;
                }
            }
        }

        if let Some(max) = self.max_length {
            if arr.len() > max {
                result.add_error(
                    ValidationError::new(
                        field,
                        format!("Array length must be at most {max}, got {}", arr.len()),
                    )
                    .with_code(codes::MAX_LENGTH)
                    .with_value(self.base.err_value(value)),
                );
                if fail_fast {
                    return result;
                }
            }
        }

        if let Some(item_validator) = &self.item_validator {
            for (i, item) in arr.iter().enumerate() {
                let path = format!("{field}[{i}]");
                result.merge(item_validator.validate(item, &path));
                if fail_fast && !result.is_valid() {
                    return result;
                }
            }
        }

        self.base.run_custom(value, field, &mut result, fail_fast);
        result
    }

    fn is_required(&self) -> bool {
        self.base.is_required()
    }

    fn is_nullable(&self) -> bool {
        self.base.is_nullable()
    }
}

/// Validator for JSON objects.
pub struct MapValidator {
    base: Base,
    schema: HashMap<String, Box<dyn Validator>>,
    strict: bool,
}

impl MapValidator {
    /// Create a new object validator.
    pub fn new() -> Self {
        Self {
            base: Base::new(),
            schema: HashMap::new(),
            strict: false,
        }
    }

    /// Add a field to the object schema.
    pub fn field(
        mut self,
        name: impl Into<String>,
        mut validator: impl Validator + 'static,
    ) -> Self {
        validator.set_fail_fast(self.base.fail_fast);
        self.schema.insert(name.into(), Box::new(validator));
        self
    }

    /// Replace the object schema wholesale.
    pub fn schema(mut self, mut schema: HashMap<String, Box<dyn Validator>>) -> Self {
        let fail_fast = self.base.fail_fast;
        for v in schema.values_mut() {
            v.set_fail_fast(fail_fast);
        }
        self.schema = schema;
        self
    }

    /// Enable or disable strict mode.
    ///
    /// When strict, unknown fields in the object produce an error.
    pub fn strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }
}

base_methods!(MapValidator);

impl Default for MapValidator {
    fn default() -> Self {
        Self::new()
    }
}

impl Validator for MapValidator {
    fn set_fail_fast(&mut self, fail_fast: bool) {
        self.base.fail_fast = fail_fast;
        for v in self.schema.values_mut() {
            v.set_fail_fast(fail_fast);
        }
    }

    fn validate(&self, value: &Value, field: &str) -> ValidationResult {
        let fail_fast = self.base.fail_fast;
        if value.is_null() {
            return self.base.handle_null(field, fail_fast);
        }

        let mut result = ValidationResult::new();

        let Some(map) = value.as_object() else {
            result.add_error(
                ValidationError::new(field, format!("Expected object, got {}", kind_name(value)))
                    .with_code(codes::TYPE)
                    .with_value(self.base.err_value(value)),
            );
            return result;
        };

        if self.strict {
            for (key, val) in map.iter() {
                if !self.schema.contains_key(key) {
                    result.add_error(
                        ValidationError::new(format!("{field}.{key}"), "Unknown field")
                            .with_code(codes::UNKNOWN_FIELD)
                            .with_value(self.base.err_value(val)),
                    );
                    if fail_fast {
                        return result;
                    }
                }
            }
        }

        for (key, validator) in &self.schema {
            let path = format!("{field}.{key}");
            if let Some(v) = map.get(key) {
                result.merge(validator.validate(v, &path));
            } else if validator.is_required() {
                result.add_error(
                    ValidationError::new(&path, "Field is required").with_code(codes::REQUIRED),
                );
            }
            if fail_fast && !result.is_valid() {
                return result;
            }
        }

        self.base.run_custom(value, field, &mut result, fail_fast);
        result
    }

    fn is_required(&self) -> bool {
        self.base.is_required()
    }

    fn is_nullable(&self) -> bool {
        self.base.is_nullable()
    }
}

/// A schema for validating top-level JSON objects.
#[derive(Default)]
pub struct Schema {
    fields: HashMap<String, Box<dyn Validator>>,
    strict: bool,
    fail_fast: bool,
}

impl Schema {
    /// Create a new schema.
    pub fn new() -> Self {
        Self {
            fields: HashMap::new(),
            strict: false,
            fail_fast: false,
        }
    }

    /// Add a field validator.
    pub fn field(
        mut self,
        name: impl Into<String>,
        mut validator: impl Validator + 'static,
    ) -> Self {
        validator.set_fail_fast(self.fail_fast);
        self.fields.insert(name.into(), Box::new(validator));
        self
    }

    /// Enable or disable strict mode.
    ///
    /// When strict, keys present in the input object but absent from the schema
    /// produce an `Unknown field` error.
    pub fn strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }

    /// Stop at the first validation error.
    ///
    /// When enabled, validation returns a result containing exactly one
    /// error. The flag is propagated to nested validators.
    pub fn fail_fast(mut self, fail_fast: bool) -> Self {
        self.fail_fast = fail_fast;
        for v in self.fields.values_mut() {
            v.set_fail_fast(fail_fast);
        }
        self
    }

    /// Validate a JSON object (`serde_json::Value` object).
    pub fn validate(&self, data: &Value) -> ValidationResult {
        let mut result = ValidationResult::new();
        let fail_fast = self.fail_fast;

        let Some(map) = data.as_object() else {
            result.add_error(
                ValidationError::new("root", format!("Expected object, got {}", kind_name(data)))
                    .with_code(codes::TYPE)
                    .with_value(data.clone()),
            );
            return result;
        };

        if self.strict {
            for (key, val) in map.iter() {
                if !self.fields.contains_key(key) {
                    result.add_error(
                        ValidationError::new(key, "Unknown field")
                            .with_code(codes::UNKNOWN_FIELD)
                            .with_value(val.clone()),
                    );
                    if fail_fast {
                        return result;
                    }
                }
            }
        }

        for (field, validator) in &self.fields {
            if let Some(value) = map.get(field) {
                result.merge(validator.validate(value, field));
            } else if validator.is_required() {
                result.add_error(
                    ValidationError::new(field, "Field is required").with_code(codes::REQUIRED),
                );
            }
            if fail_fast && !result.is_valid() {
                return result;
            }
        }

        result
    }

    /// Validate and return `Ok(())` if valid, or the full result on failure.
    pub fn validate_or_raise(&self, data: &Value) -> Result<(), ValidationResult> {
        let result = self.validate(data);
        if result.is_valid() {
            Ok(())
        } else {
            Err(result)
        }
    }

    /// Validate and return `Ok(())` if valid, or a [`ValidationErrors`]
    /// aggregate (which implements `std::error::Error`) on failure.
    pub fn try_validate(&self, data: &Value) -> Result<(), ValidationErrors> {
        self.validate(data).into_result()
    }
}

/// Factory functions for creating validators.
pub mod validators {
    use super::*;

    /// Create a string validator.
    pub fn string() -> StringValidator {
        StringValidator::new()
    }

    /// Create an integer validator.
    pub fn int() -> IntValidator {
        IntValidator::new()
    }

    /// Create a float/number validator.
    pub fn float() -> FloatValidator {
        FloatValidator::new()
    }

    /// Create a boolean validator.
    pub fn bool() -> BoolValidator {
        BoolValidator::new()
    }

    /// Create an email validator.
    pub fn email() -> EmailValidator {
        EmailValidator::new()
    }

    /// Create a URL validator.
    pub fn url() -> UrlValidator {
        UrlValidator::new()
    }

    /// Create an array validator.
    pub fn vec() -> VecValidator {
        VecValidator::new()
    }

    /// Alias for [`validators::vec`].
    pub fn list() -> VecValidator {
        VecValidator::new()
    }

    /// Create an object validator.
    pub fn map() -> MapValidator {
        MapValidator::new()
    }

    /// Alias for [`validators::map`].
    pub fn dict() -> MapValidator {
        MapValidator::new()
    }

    /// Create a UUID validator.
    pub fn uuid() -> UuidValidator {
        UuidValidator::new()
    }

    /// Create a `YYYY-MM-DD` date validator.
    pub fn date() -> DateValidator {
        DateValidator::new()
    }

    /// Create a datetime validator.
    pub fn datetime() -> DatetimeValidator {
        DatetimeValidator::new()
    }

    /// Create a numeric-string validator.
    pub fn numeric() -> NumericValidator {
        NumericValidator::new()
    }

    /// Create a validator requiring a non-empty string, array, or object.
    pub fn not_empty() -> NotEmptyValidator {
        NotEmptyValidator::new()
    }

    /// Create an enum validator over arbitrary JSON values.
    ///
    /// Named `enum_values` because `enum` is a Rust keyword; the raw
    /// identifier alias [`validators::r#enum`] is also provided.
    pub fn enum_values(values: Vec<Value>) -> EnumValidator {
        EnumValidator::new(values)
    }

    /// Alias for [`validators::enum_values`].
    #[allow(non_snake_case)]
    pub fn r#enum(values: Vec<Value>) -> EnumValidator {
        EnumValidator::new(values)
    }

    /// Create a validator that accepts the value when at least one of the
    /// given branch validators produces zero errors.
    pub fn one_of(branches: Vec<Box<dyn Validator>>) -> OneOfValidator {
        OneOfValidator::new(branches)
    }

    /// Create a string validator anchored to the given regex pattern.
    pub fn regex(re: Regex) -> StringValidator {
        StringValidator::new().pattern(re)
    }
}

// `Default` implementations for the parameterless `new()` constructors.
macro_rules! impl_default {
    ($($t:ty),* $(,)?) => {
        $(impl Default for $t {
            fn default() -> Self {
                Self::new()
            }
        })*
    };
}

impl_default!(
    StringValidator,
    IntValidator,
    FloatValidator,
    BoolValidator,
    EmailValidator,
    UrlValidator,
    NotEmptyValidator,
    VecValidator,
);

#[cfg(test)]
mod tests {
    use super::*;
    use regex::Regex;
    use serde_json::json;

    #[test]
    fn test_string_validator() {
        let validator = validators::string().min(3).max(10);
        assert!(validator.validate(&json!("hello"), "name").is_valid());
        assert!(!validator.validate(&json!("ab"), "name").is_valid());
        assert!(!validator.validate(&json!("hello world"), "name").is_valid());

        let pattern_validator = validators::string().try_pattern(r"^\d{3}-\d{4}$").unwrap();
        assert!(pattern_validator
            .validate(&json!("123-4567"), "phone")
            .is_valid());
        assert!(!pattern_validator
            .validate(&json!("12-3456"), "phone")
            .is_valid());

        let choices_validator =
            validators::string().choices(vec!["light".to_string(), "dark".to_string()]);
        assert!(choices_validator
            .validate(&json!("light"), "theme")
            .is_valid());
        assert!(!choices_validator
            .validate(&json!("red"), "theme")
            .is_valid());

        let result = validators::string().validate(&json!(42), "name");
        assert!(!result.is_valid());
        assert!(result.errors()[0]
            .message
            .contains("Expected string, got integer"));
        assert_eq!(result.errors()[0].code, codes::TYPE);
    }

    #[test]
    fn test_int_validator() {
        let validator = validators::int().min(0).max(120);
        assert!(validator.validate(&json!(25), "age").is_valid());
        assert!(!validator.validate(&json!(-1), "age").is_valid());
        assert!(!validator.validate(&json!(150), "age").is_valid());

        let result = validator.validate(&json!(1.5), "age");
        assert!(!result.is_valid());
        assert!(result.errors()[0]
            .message
            .contains("Expected integer, got number"));
        assert_eq!(result.errors()[0].code, codes::TYPE);

        let result = validator.validate(&json!("25"), "age");
        assert!(!result.is_valid());
        assert!(result.errors()[0]
            .message
            .contains("Expected integer, got string"));
    }

    #[test]
    fn test_float_validator() {
        let validator = validators::float().min(0.0).max(100.0);
        assert!(validator.validate(&json!(25.5), "score").is_valid());
        assert!(validator.validate(&json!(25), "score").is_valid());
        assert!(!validator.validate(&json!(150.0), "score").is_valid());

        let result = validator.validate(&json!("25"), "score");
        assert!(!result.is_valid());
        assert!(result.errors()[0]
            .message
            .contains("Expected number, got string"));
    }

    #[test]
    fn test_bool_validator() {
        let validator = validators::bool();
        assert!(validator.validate(&json!(true), "active").is_valid());

        let result = validator.validate(&json!("true"), "active");
        assert!(!result.is_valid());
        assert!(result.errors()[0]
            .message
            .contains("Expected boolean, got string"));
    }

    #[test]
    fn test_email_validator() {
        let validator = validators::email();
        assert!(validator
            .validate(&json!("user@example.com"), "email")
            .is_valid());

        let result = validator.validate(&json!("invalid-email"), "email");
        assert!(!result.is_valid());
        assert!(result.errors()[0].message.contains("Invalid email address"));
        assert_eq!(result.errors()[0].code, codes::EMAIL);

        let result = validator.validate(&json!(123), "email");
        assert!(!result.is_valid());
        assert!(result.errors()[0].message.contains("Expected string"));
        assert_eq!(result.errors()[0].code, codes::TYPE);
    }

    #[test]
    fn test_url_validator() {
        let validator = validators::url();
        assert!(validator
            .validate(&json!("https://example.com"), "url")
            .is_valid());

        let result = validator.validate(&json!("not-a-url"), "url");
        assert!(!result.is_valid());
        assert!(result.errors()[0].message.contains("Invalid URL"));
        assert_eq!(result.errors()[0].code, codes::URL);
    }

    #[test]
    fn test_vec_validator() {
        let validator = validators::vec()
            .item(validators::int().min(0))
            .min(1)
            .max(3);

        assert!(validator.validate(&json!([1, 2]), "items").is_valid());
        assert!(!validator.validate(&json!([]), "items").is_valid());
        assert!(!validator.validate(&json!([1, 2, 3, 4]), "items").is_valid());

        let result = validator.validate(&json!(["bad"]), "items");
        assert!(!result.is_valid());
        assert_eq!(result.errors()[0].field, "items[0]");
        assert!(result.errors()[0].message.contains("Expected integer"));
    }

    #[test]
    fn test_map_validator() {
        let validator = validators::map()
            .field("name", validators::string().min(1))
            .field("age", validators::int());

        assert!(validator
            .validate(&json!({"name": "Ada", "age": 30}), "user")
            .is_valid());

        let result = validator.validate(&json!({"name": "Ada"}), "user");
        assert!(!result.is_valid());
        assert_eq!(result.errors()[0].field, "user.age");
        assert_eq!(result.errors()[0].message, "Field is required");
        assert_eq!(result.errors()[0].code, codes::REQUIRED);
    }

    #[test]
    fn test_optional_nullable() {
        let schema = Schema::new()
            .field("name", validators::string())
            .field("bio", validators::string().optional().nullable());

        assert!(schema.validate(&json!({"name": "Ada"})).is_valid());
        assert!(schema
            .validate(&json!({"name": "Ada", "bio": null}))
            .is_valid());

        let result = schema.validate(&json!({"name": "Ada", "bio": 123}));
        assert!(!result.is_valid());
        assert!(result.errors()[0].message.contains("Expected string"));

        let required = validators::string();
        assert!(!required.validate(&Value::Null, "name").is_valid());

        let nullable = validators::string().nullable();
        assert!(nullable.validate(&Value::Null, "name").is_valid());
    }

    #[test]
    fn test_custom_validator() {
        let validator = validators::int().custom(|value| {
            if let Some(n) = value.as_i64() {
                if n % 2 == 0 {
                    return None;
                }
            }
            Some("value must be even".to_string())
        });

        assert!(validator.validate(&json!(4), "x").is_valid());

        let result = validator.validate(&json!(3), "x");
        assert!(!result.is_valid());
        assert_eq!(result.errors()[0].code, codes::CUSTOM);
    }

    #[test]
    fn test_strict_schema() {
        let schema = Schema::new()
            .field("name", validators::string())
            .strict(true);

        let result = schema.validate(&json!({"name": "Ada", "extra": 1}));
        assert!(!result.is_valid());
        assert_eq!(result.errors()[0].field, "extra");
        assert_eq!(result.errors()[0].message, "Unknown field");
        assert_eq!(result.errors()[0].code, codes::UNKNOWN_FIELD);

        assert!(schema.validate(&json!({"name": "Ada"})).is_valid());
    }

    #[test]
    fn test_strict_map() {
        let validator = validators::map()
            .field("name", validators::string())
            .strict(true);

        let result = validator.validate(&json!({"name": "Ada", "extra": 1}), "user");
        assert!(!result.is_valid());
        assert_eq!(result.errors()[0].field, "user.extra");
        assert_eq!(result.errors()[0].message, "Unknown field");
    }

    #[test]
    fn test_missing_required() {
        let schema = Schema::new()
            .field("name", validators::string())
            .field("age", validators::int());

        let result = schema.validate(&json!({"name": "Ada"}));
        assert!(!result.is_valid());
        assert!(result
            .errors()
            .iter()
            .any(|e| e.field == "age" && e.message == "Field is required"));
    }

    #[test]
    fn test_nested_map_vec_paths() {
        let schema = Schema::new().field(
            "user",
            validators::map().field("tags", validators::vec().item(validators::string().min(2))),
        );

        let result = schema.validate(&json!({"user": {"tags": ["a"]}}));
        assert!(!result.is_valid());
        assert_eq!(result.errors()[0].field, "user.tags[0]");
    }

    #[test]
    fn test_pattern_infallible() {
        let validator = validators::string().pattern(Regex::new(r"^[a-z]+$").unwrap());
        assert!(validator.validate(&json!("abc"), "code").is_valid());
        assert!(!validator.validate(&json!("ABC"), "code").is_valid());
    }

    #[test]
    fn test_validate_or_raise() {
        let schema = Schema::new().field("name", validators::string());
        assert!(schema.validate_or_raise(&json!({"name": "Ada"})).is_ok());
        assert!(schema.validate_or_raise(&json!({})).is_err());
    }

    #[test]
    fn test_fail_fast_schema() {
        let schema = Schema::new()
            .fail_fast(true)
            .field("a", validators::string().min(2))
            .field("b", validators::int().min(0));

        let result = schema.validate(&json!({"a": "x", "b": -1}));
        assert!(!result.is_valid());
        assert_eq!(result.errors().len(), 1);

        let schema_default = Schema::new()
            .field("a", validators::string().min(2))
            .field("b", validators::int().min(0));
        let result_default = schema_default.validate(&json!({"a": "x", "b": -1}));
        assert_eq!(result_default.errors().len(), 2);
    }

    #[test]
    fn test_fail_fast_map() {
        let validator = validators::map()
            .fail_fast(true)
            .field("name", validators::string().min(2))
            .field("age", validators::int().min(0));

        let result = validator.validate(&json!({"name": "x", "age": -1}), "user");
        assert!(!result.is_valid());
        assert_eq!(result.errors().len(), 1);

        let validator_default = validators::map()
            .field("name", validators::string().min(2))
            .field("age", validators::int().min(0));
        let result_default = validator_default.validate(&json!({"name": "x", "age": -1}), "user");
        assert_eq!(result_default.errors().len(), 2);
    }

    #[test]
    fn test_fail_fast_vec() {
        let validator = validators::vec()
            .fail_fast(true)
            .item(validators::int().min(0));

        let result = validator.validate(&json!([-1, -2]), "items");
        assert!(!result.is_valid());
        assert_eq!(result.errors().len(), 1);
        assert_eq!(result.errors()[0].field, "items[0]");

        let result_default = validators::vec()
            .item(validators::int().min(0))
            .validate(&json!([-1, -2]), "items");
        assert_eq!(result_default.errors().len(), 2);
    }

    #[test]
    fn test_fail_fast_nested() {
        let schema = Schema::new().fail_fast(true).field(
            "user",
            validators::map().field("tags", validators::vec().item(validators::int().min(0))),
        );

        let result = schema.validate(&json!({"user": {"tags": [-1, -2]}}));
        assert!(!result.is_valid());
        assert_eq!(result.errors().len(), 1);
        assert_eq!(result.errors()[0].field, "user.tags[0]");
    }

    #[test]
    fn test_fail_fast_leaf_stops_at_first_constraint() {
        let validator = validators::string()
            .min(5)
            .try_pattern(r"^\d+$")
            .expect("valid regex")
            .fail_fast(true);

        let result = validator.validate(&json!("ab"), "code");
        assert!(!result.is_valid());
        assert_eq!(result.errors().len(), 1);
        assert_eq!(result.errors()[0].code, codes::MIN_LENGTH);

        let result_default = validators::string()
            .min(5)
            .try_pattern(r"^\d+$")
            .expect("valid regex")
            .validate(&json!("ab"), "code");
        assert_eq!(result_default.errors().len(), 2);
    }

    #[test]
    fn test_fail_fast_propagated_after_fields_added() {
        let validator = validators::map()
            .field("name", validators::string().min(2))
            .field("age", validators::int().min(0))
            .fail_fast(true);

        let result = validator.validate(&json!({"name": "x", "age": -1}), "user");
        assert!(!result.is_valid());
        assert_eq!(result.errors().len(), 1);
    }

    #[test]
    fn test_uuid_validator() {
        let validator = validators::uuid();
        assert!(validator
            .validate(&json!("550e8400-e29b-41d4-a716-446655440000"), "id")
            .is_valid());

        let result = validator.validate(&json!("not-a-uuid"), "id");
        assert!(!result.is_valid());
        assert_eq!(result.errors()[0].code, codes::UUID);
        assert_eq!(result.errors()[0].message, "Invalid UUID: not-a-uuid");

        let result = validator.validate(&json!(42), "id");
        assert_eq!(result.errors()[0].code, codes::TYPE);
        assert_eq!(result.errors()[0].message, "Expected string, got integer");
    }

    #[test]
    fn test_date_validator() {
        let validator = validators::date();
        assert!(validator.validate(&json!("2026-09-07"), "d").is_valid());

        let result = validator.validate(&json!("2026-13-07"), "d");
        assert_eq!(result.errors()[0].code, codes::DATE);
        assert_eq!(result.errors()[0].message, "Invalid date: 2026-13-07");
    }

    #[test]
    fn test_datetime_validator() {
        let validator = validators::datetime();
        assert!(validator
            .validate(&json!("2026-09-07T10:30:00Z"), "t")
            .is_valid());
        assert!(validator
            .validate(&json!("2026-09-07T10:30:00.5+05:30"), "t")
            .is_valid());

        let result = validator.validate(&json!("2026-09-07 10:30"), "t");
        assert_eq!(result.errors()[0].code, codes::DATETIME);
        assert_eq!(
            result.errors()[0].message,
            "Invalid datetime: 2026-09-07 10:30"
        );
    }

    #[test]
    fn test_numeric_validator() {
        let validator = validators::numeric();
        assert!(validator.validate(&json!("-12.5"), "n").is_valid());
        assert!(validator.validate(&json!("1e3"), "n").is_valid());

        let result = validator.validate(&json!("12a"), "n");
        assert_eq!(result.errors()[0].code, codes::NUMERIC);
        assert_eq!(
            result.errors()[0].message,
            "Expected numeric string, got 12a"
        );

        let result = validator.validate(&json!(12), "n");
        assert_eq!(result.errors()[0].code, codes::TYPE);
    }

    #[test]
    fn test_not_empty_validator() {
        let validator = validators::not_empty();
        assert!(validator.validate(&json!("x"), "v").is_valid());
        assert!(validator.validate(&json!([1]), "v").is_valid());
        assert!(validator.validate(&json!({"k": 1}), "v").is_valid());

        for bad in [json!(""), json!([]), json!({})] {
            let result = validator.validate(&bad, "v");
            assert_eq!(result.errors()[0].code, codes::NOT_EMPTY);
            assert_eq!(result.errors()[0].message, "Value must not be empty");
        }

        let result = validator.validate(&json!(5), "v");
        assert_eq!(result.errors()[0].code, codes::TYPE);
        assert_eq!(
            result.errors()[0].message,
            "Expected string, array, or object, got integer"
        );
    }

    #[test]
    fn test_enum_validator() {
        let validator = validators::enum_values(vec![json!("a"), json!(1), json!(true)]);
        assert!(validator.validate(&json!("a"), "v").is_valid());
        assert!(validator.validate(&json!(1), "v").is_valid());

        let result = validator.validate(&json!("b"), "v");
        assert_eq!(result.errors()[0].code, codes::ENUM);
        assert_eq!(
            result.errors()[0].message,
            "Value must be one of \"a\", 1, true, got \"b\""
        );
    }

    #[test]
    fn test_one_of_validator() {
        let validator = validators::one_of(vec![
            Box::new(validators::string().min(3)),
            Box::new(validators::int().min(10)),
        ]);
        assert!(validator.validate(&json!("abc"), "v").is_valid());
        assert!(validator.validate(&json!(15), "v").is_valid());

        let result = validator.validate(&json!(5), "v");
        assert!(!result.is_valid());
        assert_eq!(result.errors().len(), 1);
        assert_eq!(result.errors()[0].code, codes::ONE_OF);
        assert_eq!(
            result.errors()[0].message,
            "Value does not match any allowed schema"
        );
    }

    #[test]
    fn test_regex_factory() {
        let validator = validators::regex(Regex::new(r"^[a-z]+$").unwrap());
        assert!(validator.validate(&json!("abc"), "code").is_valid());
        assert!(!validator.validate(&json!("ABC"), "code").is_valid());
    }

    #[test]
    fn test_sensitive_redacts_value() {
        // Messages that embed the offending value render `***` and
        // `error.value` is None.
        let result = validators::email()
            .sensitive(true)
            .validate(&json!("p@ssw0rd"), "secret");
        assert!(!result.is_valid());
        assert_eq!(result.errors()[0].message, "Invalid email address: ***");
        assert!(result.errors()[0].value.is_none());

        let result = validators::uuid()
            .sensitive(true)
            .validate(&json!("leaked"), "id");
        assert_eq!(result.errors()[0].message, "Invalid UUID: ***");
        assert!(result.errors()[0].value.is_none());

        // `choices` keeps its quotes around the redacted placeholder.
        let result = validators::string()
            .choices(vec!["a".to_string(), "b".to_string()])
            .sensitive(true)
            .validate(&json!("hunter2"), "token");
        assert_eq!(
            result.errors()[0].message,
            "Value must be one of a, b, got '***'"
        );
        assert!(result.errors()[0].value.is_none());

        // `enum` renders the bare, unquoted placeholder.
        let result = validators::enum_values(vec![json!("a"), json!(1)])
            .sensitive(true)
            .validate(&json!("hunter2"), "token");
        assert_eq!(
            result.errors()[0].message,
            "Value must be one of \"a\", 1, got ***"
        );
        assert!(result.errors()[0].value.is_none());
    }

    #[test]
    fn test_sensitive_other_messages_unchanged() {
        // Messages that do not embed the input value are unchanged.
        let result = validators::string()
            .min(5)
            .sensitive(true)
            .validate(&json!("abc"), "secret");
        assert_eq!(
            result.errors()[0].message,
            "String length must be at least 5, got 3"
        );
        assert!(result.errors()[0].value.is_none());

        // Sensitive is per-validator and not inherited by nested validators.
        let result = validators::map()
            .sensitive(true)
            .field("inner", validators::email())
            .validate(&json!({"inner": "not-an-email"}), "user");
        assert_eq!(
            result.errors()[0].message,
            "Invalid email address: not-an-email"
        );
    }

    #[test]
    fn test_pattern_input_length_cap() {
        // Over-limit inputs skip the match and produce the normal pattern
        // error. `regex` is linear-time; the cap is for spec parity.
        let long = "a".repeat(MAX_PATTERN_INPUT_LENGTH + 1);

        let result = validators::string()
            .try_pattern(r"^a+$")
            .unwrap()
            .validate(&json!(long), "s");
        assert!(!result.is_valid());
        assert_eq!(result.errors()[0].code, codes::PATTERN);

        let result = validators::email().validate(&json!(long), "e");
        assert_eq!(result.errors()[0].code, codes::EMAIL);

        let result = validators::numeric().validate(&json!(long), "n");
        assert_eq!(result.errors()[0].code, codes::NUMERIC);

        // Exactly at the limit still matches.
        let at_limit = "a".repeat(MAX_PATTERN_INPUT_LENGTH);
        assert!(validators::string()
            .try_pattern(r"^a+$")
            .unwrap()
            .validate(&json!(at_limit), "s")
            .is_valid());
    }

    #[test]
    fn test_try_validate() {
        let schema = Schema::new().field("name", validators::string());
        assert!(schema.try_validate(&json!({"name": "Ada"})).is_ok());

        let err = schema.try_validate(&json!({})).unwrap_err();
        assert_eq!(err.0.len(), 1);
        assert_eq!(err.to_string(), "name: Field is required");
    }
}