vld 0.1.3

Type-safe runtime validation library for Rust, inspired by Zod
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
[![Crates.io](https://img.shields.io/crates/v/vld?style=for-the-badge)](https://crates.io/crates/vld)
[![docs.rs](https://img.shields.io/docsrs/vld?style=for-the-badge)](https://docs.rs/vld)
[![License](https://img.shields.io/badge/license-MIT-green?style=for-the-badge)](https://github.com/s00d/vld/blob/main/LICENSE)
[![Platform](https://img.shields.io/badge/platform-macOS%20%7C%20Windows%20%7C%20Linux-blue?style=for-the-badge)](https://github.com/s00d/vld)
[![GitHub issues](https://img.shields.io/badge/github-issues-orange?style=for-the-badge)](https://github.com/s00d/vld/issues)
[![GitHub stars](https://img.shields.io/badge/github-stars-yellow?style=for-the-badge)](https://github.com/s00d/vld/stargazers)

# vld

**Type-safe runtime validation for Rust, inspired by [Zod](https://zod.dev/).**

`vld` combines schema definition with type-safe parsing. Define your validation
rules once and get both runtime checks and strongly-typed Rust structs.

[![Crates.io](https://img.shields.io/crates/v/vld.svg)](https://crates.io/crates/vld)
[![Docs.rs](https://docs.rs/vld/badge.svg)](https://docs.rs/vld)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

---

## Features

- **Zero-cost schema definitions** — the `schema!` macro generates plain Rust structs with
  built-in `parse()` methods. Or use `schema_validated!` to get lenient parsing too.
- **Error accumulation** — all validation errors are collected, not just the first one.
- **Rich primitives** — string, number, integer, boolean, literal, enum, any, custom.
- **String formats** — email, URL, UUID, IPv4, IPv6, Base64, ISO date/time/datetime, hostname, CUID2, ULID, Nano ID, emoji.
  All validated without regex by default. Every check has a `_msg` variant for custom messages.
- **Composable** — optional, nullable, nullish, default, catch, refine, super_refine, transform, pipe, preprocess, describe, `.or()`, `.and()`.
- **Collections** — arrays, tuples (up to 6), records, Map (`HashMap`), Set (`HashSet`).
- **Unions**`union(a, b)`, `union3(a, b, c)`, `.or()`, `discriminated_union("field")`, `intersection(a, b)`, `.and()`.
- **Recursive schemas**`lazy()` for self-referencing data structures (trees, graphs).
- **Dynamic objects**`strict()`, `strip()`, `passthrough()`, `pick()`, `omit()`, `extend()`, `merge()`, `partial()`, `required()`, `catchall()`, `keyof()`.
- **Custom schemas**`vld::custom(|v| ...)` for arbitrary validation logic.
- **Multiple input sources** — parse from `&str`, `String`, `&[u8]`, `Path`, `PathBuf`, or `serde_json::Value`.
- **Validate existing values**`.validate(&value)` and `.is_valid(&value)` work with any `Serialize` type. `schema!` structs get `Struct::validate(&instance)`.
- **Lenient parsing**`parse_lenient()` returns `ParseResult<T>` with the struct, per-field diagnostics, and `.save_to_file()`.
- **Error formatting**`prettify_error`, `flatten_error`, `treeify_error` utilities.
- **Custom error messages**`_msg` variants, `type_error()`, and `with_messages()` for per-check and bulk message overrides, including translations.
- **JSON Schema / OpenAPI**`JsonSchema` trait on all schema types; `json_schema()` and `to_openapi_document()` on `schema!` structs; `field_schema()` for rich object property schemas; `to_openapi_document_multi()` helper.
- **Derive macro**`#[derive(Validate)]` with `#[vld(...)]` attributes (optional `derive` feature).
- **Benchmarks** — criterion-based benchmarks included.
- **CI** — GitHub Actions workflow for testing, clippy, and formatting.
- **Minimal dependencies** — only `serde` and `serde_json`. Regex and derive macro are optional features.

## Quick Start

Add to your `Cargo.toml`:

```toml
[dependencies]
vld = "0.1"
```

### Optional Features

All features are **disabled** by default:

| Feature       | Description                                                                                                                                                         |
|---------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `serialize`   | Adds `#[derive(Serialize)]` on error/result types, enables `VldSchema::validate()`/`is_valid()`, `ParseResult::save_to_file()`/`to_json_string()`/`to_json_value()` |
| `deserialize` | Adds `#[derive(Deserialize)]` on error/result types                                                                                                                 |
| `openapi`     | Enables `JsonSchema` trait, `to_json_schema()`, `json_schema()`, `to_openapi_document()`, `field_schema()`                                                          |
| `diff`        | Schema diffing — compare two JSON Schemas to detect breaking vs non-breaking changes                                                                                |
| `regex`       | Custom regex patterns via `.regex()` (uses `regex-lite`)                                                                                                            |
| `derive`      | `#[derive(Validate)]` procedural macro                                                                                                                              |
| `chrono`      | `ZDate` / `ZDateTime` types with `chrono` parsing                                                                                                                   |

Enable features as needed:

```toml
[dependencies]
vld = { version = "0.1", features = ["serialize", "openapi"] }
```

### Basic Usage

```rust
use vld::prelude::*;

// Define a validated struct
vld::schema! {
    #[derive(Debug)]
    pub struct User {
        pub name: String => vld::string().min(2).max(50),
        pub email: String => vld::string().email(),
        pub age: Option<i64> => vld::number().int().gte(18).optional(),
    }
}

// Parse from a JSON string
let user = User::parse(r#"{"name": "Alex", "email": "alex@example.com"}"#).unwrap();
assert_eq!(user.name, "Alex");
assert_eq!(user.age, None);

// Errors are accumulated
let err = User::parse(r#"{"name": "A", "email": "bad"}"#).unwrap_err();
assert!(err.issues.len() >= 2);
```

### Nested Structs

```rust
use vld::prelude::*;

vld::schema! {
    #[derive(Debug)]
    pub struct Address {
        pub city: String => vld::string().min(1),
        pub zip: String  => vld::string().len(6),
    }
}

vld::schema! {
    #[derive(Debug)]
    pub struct User {
        pub name: String       => vld::string().min(2),
        pub address: Address   => vld::nested(Address::parse_value),
    }
}

let user = User::parse(r#"{
    "name": "Alex",
    "address": {"city": "New York", "zip": "100001"}
}"#).unwrap();
```

## Primitives

### String

```rust
vld::string()
    .min(3)                 // minimum length
    .max(100)               // maximum length
    .len(10)                // exact length
    .email()                // email format
    .url()                  // URL format (http/https)
    .uuid()                 // UUID format
    .ipv4()                 // IPv4 address
    .ipv6()                 // IPv6 address
    .base64()               // Base64 string
    .iso_date()             // ISO 8601 date (YYYY-MM-DD)
    .iso_time()             // ISO 8601 time (HH:MM:SS)
    .iso_datetime()         // ISO 8601 datetime
    .hostname()             // valid hostname
    .cuid2()                // CUID2 format
    .ulid()                 // ULID format (26 chars, Crockford Base32)
    .nanoid()               // Nano ID format (alphanumeric + _-)
    .emoji()                // must contain emoji
    .starts_with("prefix")  // must start with
    .ends_with("suffix")    // must end with
    .contains("sub")        // must contain
    .non_empty()            // must not be empty
    .trim()                 // trim whitespace before validation
    .to_lowercase()         // convert to lowercase
    .to_uppercase()         // convert to uppercase
    .coerce()               // coerce numbers/booleans to string
```

### Number

```rust
vld::number()
    .min(0.0)       // minimum (inclusive)
    .max(100.0)     // maximum (inclusive)
    .gt(0.0)        // greater than (exclusive)
    .lt(100.0)      // less than (exclusive)
    .positive()     // > 0
    .negative()     // < 0
    .non_negative() // >= 0
    .finite()       // not NaN or infinity
    .multiple_of(5.0)
    .safe()         // JS safe integer range (-(2^53-1) to 2^53-1)
    .int()          // switch to integer mode (i64)
    .coerce()       // coerce strings/booleans to number
```

### Integer

```rust
vld::number().int()
    .min(0)
    .max(100)
    .gte(18)
    .positive()
```

### Boolean

```rust
vld::boolean()
    .coerce()  // "true"/"false"/"1"/"0" -> bool
```

### Literal

```rust
vld::literal("admin")   // exact string match
vld::literal(42i64)      // exact integer match
vld::literal(true)       // exact boolean match
```

### Enum

```rust
vld::enumeration(&["admin", "user", "moderator"])
```

### Any

```rust
vld::any()  // accepts any JSON value
```

## Modifiers

```rust
// Optional: null/missing -> None
vld::string().optional()

// Nullable: null -> None
vld::string().nullable()

// Nullish: both optional + nullable
vld::string().nullish()

// Default: null/missing -> default value
vld::string().with_default("fallback".to_string())

// Catch: ANY error -> fallback value
vld::string().min(3).catch("default".to_string())
```

## Collections

### Array

```rust
vld::array(vld::string().non_empty())
    .min_len(1)
    .max_len(10)
    .len(5)       // exact length
    .non_empty()  // alias for min_len(1)
```

### Tuple

```rust
// Tuples of 1-6 elements
let schema = (vld::string(), vld::number().int(), vld::boolean());
let (s, n, b) = schema.parse(r#"["hello", 42, true]"#).unwrap();
```

### Record

```rust
vld::record(vld::number().int().positive())
    .min_keys(1)
    .max_keys(10)
```

### Map

```rust
// Input: [["a", 1], ["b", 2]] -> HashMap
vld::map(vld::string(), vld::number().int())
```

### Set

```rust
// Input: ["a", "b", "a"] -> HashSet {"a", "b"}
vld::set(vld::string().min(1))
    .min_size(1)
    .max_size(10)
```

## Combinators

### Union

```rust
// Union of 2 types
let schema = vld::union(vld::string(), vld::number().int());
// Returns Either<String, i64>

// Union of 3 types
let schema = vld::union3(vld::string(), vld::number(), vld::boolean());
// Returns Either3<String, f64, bool>
```

### `union!` macro

For convenience, use the `union!` macro to combine 2–6 schemas without
nesting calls manually. The macro dispatches to `union()` / `union3()` or
nests them automatically for higher arities:

```rust
use vld::prelude::*;

// 2 schemas — same as vld::union(a, b)
let s2 = vld::union!(vld::string(), vld::number());

// 3 schemas — same as vld::union3(a, b, c)
let s3 = vld::union!(vld::string(), vld::number(), vld::boolean());

// 4 schemas — nested automatically
let s4 = vld::union!(
    vld::string(),
    vld::number(),
    vld::boolean(),
    vld::number().int(),
);

// 5 and 6 schemas work the same way
let s5 = vld::union!(
    vld::string(),
    vld::number(),
    vld::boolean(),
    vld::number().int(),
    vld::literal("hello"),
);
```

You can also use the method chaining equivalent `.or()` for two schemas:

```rust
let schema = vld::string().or(vld::number().int());
```

### Discriminated Union

```rust
// Efficient union by discriminator field
let schema = vld::discriminated_union("type")
    .variant_str("dog", vld::object()
        .field("type", vld::literal("dog"))
        .field("bark", vld::boolean()))
    .variant_str("cat", vld::object()
        .field("type", vld::literal("cat"))
        .field("lives", vld::number().int()));
```

### Intersection

```rust
// Input must satisfy both schemas
let schema = vld::intersection(
    vld::string().min(3),
    vld::string().email(),
);
```

### Refine

```rust
vld::number().int().refine(|n| n % 2 == 0, "Must be even")
```

### Super Refine

```rust
// Produce multiple errors in one check
vld::string().super_refine(|s, errors| {
    if s.len() < 3 {
        errors.push(IssueCode::Custom { code: "short".into() }, "Too short");
    }
    if !s.contains('@') {
        errors.push(IssueCode::Custom { code: "no_at".into() }, "Missing @");
    }
})
```

### Transform

```rust
vld::string().transform(|s| s.len())  // String -> usize
```

### Pipe

```rust
// Chain schemas: output of first -> input of second
vld::string()
    .transform(|s| s.len())
    .pipe(vld::number().min(3.0))
```

### Preprocess

```rust
vld::preprocess(
    |v| match v.as_str() {
        Some(s) => serde_json::json!(s.trim()),
        None => v.clone(),
    },
    vld::string().min(1),
)
```

### Lazy (Recursive)

```rust
// Self-referencing schemas for trees, graphs, etc.
fn tree() -> vld::object::ZObject {
    vld::object()
        .field("value", vld::number().int())
        .field("children", vld::array(vld::lazy(tree)))
}
```

### Describe

```rust
// Attach metadata (does not affect validation)
vld::string().min(3).describe("User's full name")
```

## Dynamic Object

For runtime-defined schemas (without compile-time type safety):

```rust
let obj = vld::object()
    .field("name", vld::string().min(1))
    .field("score", vld::number().min(0.0).max(100.0))
    .strict();    // reject unknown fields
    // .strip()   // remove unknown fields (default)
    // .passthrough()  // keep unknown fields as-is

// Object manipulation
let base = vld::object().field("a", vld::string()).field("b", vld::number());
base.pick(&["a"])          // keep only "a"
base.omit("b")             // remove "b"
base.partial()             // all fields become optional
base.required()            // all fields must not be null (opposite of partial)
base.deep_partial()        // partial (nested objects: apply separately)
base.extend(other_object)  // merge fields from another schema
base.merge(other_object)   // alias for extend
base.catchall(vld::string()) // validate unknown fields with a schema
base.keyof()               // Vec<String> of field names
```

## Per-Field Validation & Lenient Parsing

Use `schema_validated!` for zero-duplication, or `schema!` + `impl_validate_fields!` separately:

```rust
use vld::prelude::*;

// Option A: single macro (requires Serialize + Default on field types)
vld::schema_validated! {
    #[derive(Debug, serde::Serialize)]
    pub struct User {
        pub name: String     => vld::string().min(2),
        pub email: String    => vld::string().email(),
        pub age: Option<i64> => vld::number().int().gte(18).optional(),
    }
}

// Option B: separate macros (more control)
// vld::schema! { ... }
// vld::impl_validate_fields!(User { name: String => ..., });
```

### validate_fields — per-field diagnostics

```rust
let results = User::validate_fields(r#"{"name": "X", "email": "bad"}"#).unwrap();
for f in &results {
    println!("{}", f);
}
// Output:
//   ✖ name: String must be at least 2 characters (received: "X")
//   ✖ email: Invalid email address (received: "bad")
//   ✔ age: null
```

### parse_lenient — returns a `ParseResult<T>`

`parse_lenient` returns a [`ParseResult<T>`] — a wrapper around the struct and
per-field diagnostics. You can inspect it, convert to JSON, or save to a file
**whenever you want**.

```rust
let result = User::parse_lenient(r#"{"name": "X", "email": "bad"}"#).unwrap();

// Inspect
println!("valid: {}", result.is_valid());        // false
println!("errors: {}", result.error_count());     // 2
println!("value: {:?}", result.value);            // User { name: "", email: "", age: None }

// Per-field diagnostics
for f in result.fields() {
    println!("{}", f);
}

// Only errors
for f in result.error_fields() {
    println!("{}", f);
}

// Display trait prints a summary
println!("{}", result);

// Convert to JSON string
let json = result.to_json_string().unwrap();

// Save to file at any time
result.save_to_file(std::path::Path::new("output.json")).unwrap();

// Or extract the struct
let user = result.into_value();
```

**`ParseResult<T>` methods:**

| Method                | Description                                           |
|-----------------------|-------------------------------------------------------|
| `.value`              | The constructed struct (invalid fields use `Default`) |
| `.fields()`           | All per-field results (`&[FieldResult]`)              |
| `.valid_fields()`     | Only passed fields                                    |
| `.error_fields()`     | Only failed fields                                    |
| `.is_valid()`         | `true` if all fields passed                           |
| `.has_errors()`       | `true` if any field failed                            |
| `.valid_count()`      | Number of valid fields                                |
| `.error_count()`      | Number of invalid fields                              |
| `.save_to_file(path)` | Serialize to JSON file (requires `Serialize`)         |
| `.to_json_string()`   | Serialize to JSON string                              |
| `.to_json_value()`    | Serialize to `serde_json::Value`                      |
| `.into_value()`       | Consume and return the inner struct                   |
| `.into_parts()`       | Consume and return `(T, Vec<FieldResult>)`            |

## Single-Field Extraction

Parse the entire schema first, then extract individual fields from the result.
Use `parse_lenient` + `.field("name")` to inspect a specific field's validation
status — even when other fields are invalid:

```rust
use vld::prelude::*;

// Define and register per-field validation
vld::schema! {
    #[derive(Debug, serde::Serialize, Default)]
    pub struct User {
        pub name: String     => vld::string().min(2),
        pub email: String    => vld::string().email(),
        pub age: Option<i64> => vld::number().int().gte(18).optional(),
    }
}
vld::impl_validate_fields!(User {
    name  : String      => vld::string().min(2),
    email : String      => vld::string().email(),
    age   : Option<i64> => vld::number().int().gte(18).optional(),
});

// Strict parse — access fields directly
let user = User::parse(r#"{"name":"Alex","email":"a@b.com","age":30}"#).unwrap();
println!("{}", user.name);  // "Alex"

// Lenient parse — some fields may be invalid
let result = User::parse_lenient(r#"{"name":"X","email":"bad","age":25}"#).unwrap();

// The struct is always available (invalid fields use Default)
println!("{}", result.value.age.unwrap()); // 25 — valid, kept as-is

// Check a specific field
let name_field = result.field("name").unwrap();
println!("{}", name_field);       // ✖ name: String must be at least 2 characters
println!("{}", name_field.is_ok()); // false

let age_field = result.field("age").unwrap();
println!("{}", age_field);        // ✔ age: 25
println!("{}", age_field.is_ok()); // true
```

## Error Formatting

```rust
use vld::format::{prettify_error, flatten_error, treeify_error};

match User::parse(bad_input) {
    Err(e) => {
        // Human-readable with markers
        println!("{}", prettify_error(&e));
        // ✖ String must be at least 2 characters
        //   → at .name, received "A"

        // Flat map: field -> Vec<message>
        let flat = flatten_error(&e);
        for (field, msgs) in &flat.field_errors {
            println!("{}: {:?}", field, msgs);
        }

        // Tree structure mirroring the schema
        let tree = treeify_error(&e);
    }
    _ => {}
}
```

## Input Sources

Schemas accept any type implementing `VldInput`:

```rust
// JSON string
User::parse(r#"{"name": "Alex", "email": "a@b.com"}"#)?;

// serde_json::Value
let val = serde_json::json!({"name": "Alex", "email": "a@b.com"});
User::parse(&val)?;

// File path
User::parse(std::path::Path::new("data/user.json"))?;

// Byte slice
User::parse(b"{\"name\": \"Alex\", \"email\": \"a@b.com\"}" as &[u8])?;
```

## Validate Existing Rust Values

> Requires the `serialize` feature.

Instead of only parsing JSON, you can validate any existing Rust value using
`.validate()` and `.is_valid()`. The value is serialized to JSON internally,
then validated against the schema.

### On any schema

```rust
use vld::prelude::*;

// Validate a Vec
let schema = vld::array(vld::number().int().positive()).min_len(1).max_len(5);
assert!(schema.is_valid(&vec![1, 2, 3]));
assert!(schema.validate(&vec![-1, 0]).is_err());

// Validate a String
let email = vld::string().email();
assert!(email.is_valid(&"user@example.com"));
assert!(!email.is_valid(&"bad"));

// Validate a number
let age = vld::number().int().min(18).max(120);
assert!(age.is_valid(&25));
assert!(!age.is_valid(&10));

// Validate a HashMap
let schema = vld::record(vld::number().positive());
let mut map = std::collections::HashMap::new();
map.insert("score", 95.5);
assert!(schema.is_valid(&map));
```

### On `schema!` structs

Structs with `#[derive(serde::Serialize)]` get `validate()` and `is_valid()`
that check an already-constructed instance against the schema:

```rust
use vld::prelude::*;

vld::schema! {
    #[derive(Debug, serde::Serialize)]
    pub struct User {
        pub name: String => vld::string().min(2),
        pub email: String => vld::string().email(),
    }
}

// Construct a struct normally (bypassing parse)
let user = User {
    name: "A".to_string(),        // too short
    email: "bad".to_string(),     // invalid email
};

// Validate it
assert!(!User::is_valid(&user));
let err = User::validate(&user).unwrap_err();
// err contains: .name: too short, .email: invalid

// Also works with serde_json::Value or any Serialize type
let json = serde_json::json!({"name": "Bob", "email": "bob@test.com"});
assert!(User::is_valid(&json));
```

## `impl_rules!` — Attach Validation to Existing Structs

Use `impl_rules!` to add `.validate()` and `.is_valid()` to a struct you
already have. No need to redefine it — just list the field rules:

```rust
use vld::prelude::*;

// No #[derive(Serialize)] or #[derive(Debug)] required
struct Product {
    name: String,
    price: f64,
    quantity: i64,
    tags: Vec<String>,
}

vld::impl_rules!(Product {
    name     => vld::string().min(2).max(100),
    price    => vld::number().positive(),
    quantity => vld::number().int().non_negative(),
    tags     => vld::array(vld::string().min(1)).max_len(10),
});

let p = Product {
    name: "Widget".into(),
    price: 9.99,
    quantity: 5,
    tags: vec!["sale".into()],
};
assert!(p.is_valid());

let bad = Product {
    name: "X".into(),
    price: -1.0,
    quantity: -1,
    tags: vec!["".into()],
};
assert!(!bad.is_valid());
let err = bad.validate().unwrap_err();
for issue in &err.issues {
    let path: String = issue.path.iter().map(|p| p.to_string()).collect();
    println!("{}: {}", path, issue.message);
}
// .name: String must be at least 2 characters
// .price: Number must be positive
// .quantity: Number must be non-negative
// .tags[0]: String must be at least 1 characters
```

The struct itself does **not** need `Serialize` or `Debug` — each field is
serialized individually (standard types like `String`, `f64`, `Vec<T>` already
implement `Serialize`). You can use all schema features inside `impl_rules!`:
`with_messages()`, `type_error()`, `refine()`, etc.

## Chain Syntax: `.or()` / `.and()`

```rust
// Union via method chaining
let schema = vld::string().or(vld::number().int());
// Equivalent to vld::union(vld::string(), vld::number().int())

// Intersection via method chaining
let bounded = vld::string().min(3).and(vld::string().email());
// Input must satisfy both constraints
```

## Custom Schema

Create a schema from any closure:

```rust
let even = vld::custom(|v: &serde_json::Value| {
    let n = v.as_i64().ok_or("Expected integer")?;
    if n % 2 == 0 { Ok(n) } else { Err("Must be even".into()) }
});
assert_eq!(even.parse("4").unwrap(), 4);
assert!(even.parse("5").is_err());
```

## JSON Schema / OpenAPI Generation

> Requires the `openapi` feature.

Generate [JSON Schema](https://json-schema.org/) (compatible with **OpenAPI 3.1**)
from any `vld` schema via the `JsonSchema` trait:

```rust
use vld::prelude::*;  // imports JsonSchema trait

// Any individual schema
let js = vld::string().min(2).max(50).email().json_schema();
// {"type": "string", "minLength": 2, "maxLength": 50, "format": "email"}

// Collections
let js = vld::array(vld::number().int().positive()).min_len(1).json_schema();
// {"type": "array", "items": {"type": "integer", ...}, "minItems": 1}

// Modifiers (optional wraps with oneOf)
let js = vld::string().email().optional().json_schema();
// {"oneOf": [{"type": "string", "format": "email"}, {"type": "null"}]}

// Unions → oneOf, Intersections → allOf
let js = vld::union(vld::string(), vld::number()).json_schema();
// {"oneOf": [{"type": "string"}, {"type": "number"}]}
```

### Object field schemas

Use `field_schema()` (instead of `field()`) to include full JSON Schema for
each property:

```rust
let js = vld::object()
    .field_schema("email", vld::string().email().min(5))
    .field_schema("score", vld::number().min(0.0).max(100.0))
    .strict()
    .json_schema();
// {"type": "object", "properties": {"email": {...}, "score": {...}}, ...}
```

### `schema!` macro — struct-level JSON Schema

Structs defined via `schema!` automatically get `json_schema()` and
`to_openapi_document()` class methods:

```rust
use vld::prelude::*;

vld::schema! {
    #[derive(Debug)]
    pub struct User {
        pub name: String => vld::string().min(2).max(100),
        pub email: String => vld::string().email(),
        pub age: i64 => vld::number().int().min(0),
    }
}

// Full JSON Schema for the struct
let schema = User::json_schema();
// {
//   "type": "object",
//   "required": ["name", "email", "age"],
//   "properties": {
//     "name": {"type": "string", "minLength": 2, "maxLength": 100},
//     "email": {"type": "string", "format": "email"},
//     "age": {"type": "integer", "minimum": 0}
//   }
// }

// Wrap in a minimal OpenAPI 3.1 document
let doc = User::to_openapi_document();
// {"openapi": "3.1.0", "components": {"schemas": {"User": {...}}}, ...}
```

### Multi-schema OpenAPI document

```rust
use vld::json_schema::to_openapi_document_multi;

let doc = to_openapi_document_multi(&[
    ("User", User::json_schema()),
    ("Address", Address::json_schema()),
]);
```

### `JsonSchema` trait

The trait is implemented for all core types: `ZString`, `ZNumber`, `ZInt`,
`ZBoolean`, `ZEnum`, `ZAny`, `ZArray`, `ZRecord`, `ZSet`, `ZObject`,
`ZOptional`, `ZNullable`, `ZNullish`, `ZDefault`, `ZCatch`, `ZRefine`,
`ZTransform`, `ZDescribe`, `ZUnion2`, `ZUnion3`, `ZIntersection`,
`NestedSchema`.

## Custom Error Messages

Error messages are configured at the **schema level**, not after validation.
There are three mechanisms:

### 1. `_msg` variants — per-check custom messages

Every validation method has a `_msg` variant that accepts a custom error message:

```rust
use vld::prelude::*;

let schema = vld::string()
    .min_msg(3, "Name must be at least 3 characters")
    .max_msg(50, "Name is too long")
    .email_msg("Please enter a valid email");

let err = schema.parse(r#""ab""#).unwrap_err();
// -> "Name must be at least 3 characters"
// -> "Please enter a valid email"
```

Available on all string checks (`email_msg`, `url_msg`, `uuid_msg`, `ipv4_msg`, etc.)
and number checks are set via `with_messages` (see below).

### 2. `type_error()` — custom type mismatch message

Override the "Expected X, received Y" message when the input has the wrong JSON type:

```rust
use vld::prelude::*;

let schema = vld::string().type_error("This field requires text");
let err = schema.parse("42").unwrap_err();
assert!(err.issues[0].message.contains("This field requires text"));

let schema = vld::number().type_error("Age must be a number");
let schema = vld::number().int().int_error("Whole numbers only");
```

### 3. `with_messages()` — bulk override by check key

Override multiple messages at once using check category keys. The closure receives
the key and returns `Some(new_message)` to replace, or `None` to keep the original:

```rust
use vld::prelude::*;

let schema = vld::string().min(5).max(100).email()
    .with_messages(|key| match key {
        "too_small" => Some("Too short!".into()),
        "too_big" => Some("Too long!".into()),
        "invalid_email" => Some("Bad email!".into()),
        _ => None,
    });
```

Works on numbers too — great for translations:

```rust
use vld::prelude::*;

let schema = vld::number().min(1.0).max(100.0)
    .with_messages(|key| match key {
        "too_small" => Some("Значение должно быть не менее 1".into()),
        "too_big" => Some("Значение не должно превышать 100".into()),
        _ => None,
    });
```

For integers, the key `"not_int"` overrides the "not an integer" message:

```rust
use vld::prelude::*;

let schema = vld::number().int().min(1).max(10)
    .with_messages(|key| match key {
        "too_small" => Some("Minimum is 1".into()),
        "not_int" => Some("No decimals allowed".into()),
        _ => None,
    });
```

### 4. In objects — per-field custom messages

Combine `type_error()` and `with_messages()` on individual fields:

```rust
use vld::prelude::*;

let schema = vld::object()
    .field("name", vld::string().min(2)
        .type_error("Name must be text")
        .with_messages(|k| match k {
            "too_small" => Some("Name is too short".into()),
            _ => None,
        }))
    .field("age", vld::number().int().min(18)
        .type_error("Age must be a number")
        .with_messages(|k| match k {
            "too_small" => Some("Must be 18 or older".into()),
            _ => None,
        }));
```

### String check keys

| Key                    | Check          |
|------------------------|----------------|
| `too_small`            | `min`          |
| `too_big`              | `max`          |
| `invalid_length`       | `len`          |
| `invalid_email`        | `email`        |
| `invalid_url`          | `url`          |
| `invalid_uuid`         | `uuid`         |
| `invalid_regex`        | `regex`        |
| `invalid_starts_with`  | `starts_with`  |
| `invalid_ends_with`    | `ends_with`    |
| `invalid_contains`     | `contains`     |
| `non_empty`            | `non_empty`    |
| `invalid_ipv4`         | `ipv4`         |
| `invalid_ipv6`         | `ipv6`         |
| `invalid_base64`       | `base64`       |
| `invalid_iso_date`     | `iso_date`     |
| `invalid_iso_datetime` | `iso_datetime` |
| `invalid_iso_time`     | `iso_time`     |
| `invalid_hostname`     | `hostname`     |
| `invalid_cuid2`        | `cuid2`        |
| `invalid_ulid`         | `ulid`         |
| `invalid_nanoid`       | `nanoid`       |
| `invalid_emoji`        | `emoji`        |

### Number check keys

| Key                | Check              |
|--------------------|--------------------|
| `too_small`        | `min`, `gt`, `gte` |
| `too_big`          | `max`, `lt`, `lte` |
| `not_positive`     | `positive`         |
| `not_negative`     | `negative`         |
| `not_non_negative` | `non_negative`     |
| `not_non_positive` | `non_positive`     |
| `not_finite`       | `finite`           |
| `not_multiple_of`  | `multiple_of`      |
| `not_safe`         | `safe`             |
| `not_int`          | `int` (ZInt only)  |

## Derive Macro

Enable the `derive` feature for `#[derive(Validate)]`:

```toml
[dependencies]
vld = { version = "0.1", features = ["derive"] }
```

```rust
use vld::Validate;

#[derive(Debug, Default, serde::Serialize, Validate)]
struct User {
    #[vld(vld::string().min(2).max(50))]
    name: String,
    #[vld(vld::string().email())]
    email: String,
    #[vld(vld::number().int().gte(18).optional())]
    age: Option<i64>,
}

// Generates: vld_parse(), parse_value(), validate_fields(), parse_lenient()
let user = User::vld_parse(r#"{"name": "Alex", "email": "a@b.com"}"#).unwrap();
```

### Derive + utoipa (OpenAPI)

`#[derive(Validate)]` works with `impl_to_schema!` from `vld-utoipa`, including
full support for `#[serde(rename_all = "...")]`. Enable both `derive` and `openapi` features:

```toml
[dependencies]
vld = { version = "0.1", features = ["derive", "openapi"] }
vld-utoipa = "0.1"
utoipa = "5"
```

```rust
use vld::Validate;
use vld_utoipa::impl_to_schema;

#[derive(Debug, serde::Deserialize, Validate)]
#[serde(rename_all = "camelCase")]
struct UpdateLocationRequest {
    #[vld(vld::string().min(1).max(255))]
    name: String,
    #[vld(vld::string())]
    city: String,
    #[vld(vld::string())]
    street_address: String,
    #[vld(vld::number().int().non_negative().min(1).max(9999))]
    street_number: i64,
    #[vld(vld::string().optional())]
    street_number_addition: Option<String>,
    #[vld(vld::boolean())]
    is_active: bool,
}

impl_to_schema!(UpdateLocationRequest);
// OpenAPI schema uses camelCase keys: "streetAddress", "streetNumber", etc.
// Validation also expects camelCase JSON input.
```

## Optional Regex Support

> Requires the `regex` feature.

By default, `vld` validates all string formats (email, UUID, etc.) without regex.
If you need custom regex patterns via `.regex()`, enable the `regex` feature:

```toml
[dependencies]
vld = { version = "0.1", features = ["regex"] }
```

```rust
let schema = vld::string().regex(vld::regex_lite::Regex::new(r"^\d{3}-\d{4}$").unwrap());
```

## Running the Playground

```bash
cargo run --example playground
```

## Benchmarks

```bash
cargo bench
```

## Workspace Crates

The `vld` project is organized as a Cargo workspace with several crates:

| Crate | Version | Description |
|-------|---------|-------------|
| [`vld`]. | [![crates.io]https://img.shields.io/crates/v/vld?style=flat-square]https://crates.io/crates/vld | Core validation library — schemas, parsers, macros, error handling, i18n |
| [`vld-derive`]crates/vld-derive/ | [![crates.io]https://img.shields.io/crates/v/vld-derive?style=flat-square]https://crates.io/crates/vld-derive | Procedural macro `#[derive(Validate)]` for automatic struct validation |
| [`vld-axum`]crates/vld-axum/ | [![crates.io]https://img.shields.io/crates/v/vld-axum?style=flat-square]https://crates.io/crates/vld-axum | [Axum]https://github.com/tokio-rs/axum — extractors `VldJson`, `VldQuery`, `VldPath`, `VldForm`, `VldHeaders`, `VldCookie` |
| [`vld-actix`]crates/vld-actix/ | [![crates.io]https://img.shields.io/crates/v/vld-actix?style=flat-square]https://crates.io/crates/vld-actix | [Actix-web]https://actix.rs/ — extractors `VldJson`, `VldQuery`, `VldPath`, `VldForm`, `VldHeaders`, `VldCookie` |
| [`vld-rocket`]crates/vld-rocket/ | [![crates.io]https://img.shields.io/crates/v/vld-rocket?style=flat-square]https://crates.io/crates/vld-rocket | [Rocket]https://rocket.rs/ — extractors `VldJson`, `VldQuery`, `VldForm` + JSON error catchers |
| [`vld-poem`]crates/vld-poem/ | [![crates.io]https://img.shields.io/crates/v/vld-poem?style=flat-square]https://crates.io/crates/vld-poem | [Poem]https://docs.rs/poem — extractors `VldJson`, `VldQuery`, `VldForm`, `VldPath`, `VldHeaders`, `VldCookie` |
| [`vld-warp`]crates/vld-warp/ | [![crates.io]https://img.shields.io/crates/v/vld-warp?style=flat-square]https://crates.io/crates/vld-warp | [Warp]https://docs.rs/warp — filters `vld_json`, `vld_query`, `vld_param`, `vld_path` + `handle_rejection` |
| [`vld-salvo`]crates/vld-salvo/ | [![crates.io]https://img.shields.io/crates/v/vld-salvo?style=flat-square]https://crates.io/crates/vld-salvo | [Salvo]https://salvo.rs/ — extractors `VldJson`, `VldQuery`, `VldPath`, `VldForm`, `VldHeaders`, `VldCookie` |
| [`vld-tower`]crates/vld-tower/ | [![crates.io]https://img.shields.io/crates/v/vld-tower?style=flat-square]https://crates.io/crates/vld-tower | Universal [Tower]https://docs.rs/tower middleware — validate JSON bodies in any Tower-compatible framework |
| [`vld-diesel`]crates/vld-diesel/ | [![crates.io]https://img.shields.io/crates/v/vld-diesel?style=flat-square]https://crates.io/crates/vld-diesel | [Diesel]https://diesel.rs/ ORM — `Validated<S, T>` wrapper, `VldText`, `VldInt` column types |
| [`vld-sea`]crates/vld-sea/ | [![crates.io]https://img.shields.io/crates/v/vld-sea?style=flat-square]https://crates.io/crates/vld-sea | [SeaORM]https://www.sea-ql.org/SeaORM/ — validate `ActiveModel` before insert/update |
| [`vld-utoipa`]crates/vld-utoipa/ | [![crates.io]https://img.shields.io/crates/v/vld-utoipa?style=flat-square]https://crates.io/crates/vld-utoipa | [utoipa]https://docs.rs/utoipa — auto-generate `ToSchema` from `vld` definitions |
| [`vld-config`]crates/vld-config/ | [![crates.io]https://img.shields.io/crates/v/vld-config?style=flat-square]https://crates.io/crates/vld-config | Config validation — TOML/YAML/JSON/ENV via [config-rs]https://docs.rs/config or [figment]https://docs.rs/figment |
| [`vld-clap`]crates/vld-clap/ | [![crates.io]https://img.shields.io/crates/v/vld-clap?style=flat-square]https://crates.io/crates/vld-clap | [Clap]https://docs.rs/clap — validate CLI arguments via `#[derive(Validate)]` |
| [`vld-tauri`]crates/vld-tauri/ | [![crates.io]https://img.shields.io/crates/v/vld-tauri?style=flat-square]https://crates.io/crates/vld-tauri | [Tauri]https://tauri.app/ — validate IPC commands, events, state, channels, plugin config |
| [`vld-ts`]crates/vld-ts/ | [![crates.io]https://img.shields.io/crates/v/vld-ts?style=flat-square]https://crates.io/crates/vld-ts | TypeScript codegen — generates [Zod]https://zod.dev/ schemas from `vld` JSON Schema output |
| [`vld-fake`]crates/vld-fake/ | [![crates.io]https://img.shields.io/crates/v/vld-fake?style=flat-square]https://crates.io/crates/vld-fake | Fake data generation — `User::fake()`, `fake_many()`, `fake_seeded()` with realistic dictionaries |
| [`vld-http-common`]crates/vld-http-common/ | [![crates.io]https://img.shields.io/crates/v/vld-http-common?style=flat-square]https://crates.io/crates/vld-http-common | Shared HTTP helpers — query parsing, value coercion, error formatting (used by web crates) |

### vld-derive

Enable with `features = ["derive"]`. Provides `#[derive(Validate)]` with `#[vld(...)]` attributes
on struct fields. Supports `#[serde(rename)]` and `#[serde(rename_all)]` for JSON key mapping.
When `openapi` feature is also enabled, generates `json_schema()` and `to_openapi_document()` methods,
making it fully compatible with `vld-utoipa`'s `impl_to_schema!`.

```rust
use vld::Validate;

#[derive(Debug, Default, serde::Serialize, Validate)]
struct User {
    #[vld(vld::string().min(2).max(50))]
    name: String,
    #[vld(vld::string().email())]
    email: String,
}
```

### vld-axum

Validation extractors for Axum web framework. Automatically validates request data
and returns `422 Unprocessable Entity` with structured JSON errors on failure.

```toml
[dependencies]
vld-axum = "0.1"
```

```rust
use vld_axum::prelude::*;

async fn handler(VldJson(body): VldJson<MySchema>) -> impl IntoResponse {
    // body is already validated
}
```

### vld-actix

Validation extractors for Actix-web framework. Same API surface as `vld-axum`.

```toml
[dependencies]
vld-actix = "0.1"
```

```rust
use vld_actix::prelude::*;

async fn handler(VldJson(body): VldJson<MySchema>) -> impl Responder {
    // body is already validated
}
```

### vld-diesel

Integration with Diesel ORM. Validate data before insert/update, validate rows after load,
and use validated column types (`VldText<S>`, `VldInt<S>`) that enforce constraints at the type level.

```toml
[dependencies]
vld-diesel = { version = "0.1", features = ["sqlite"] }
```

```rust
use vld_diesel::prelude::*;

let validated = validate_insert::<MySchema, _>(&new_row)?;
diesel::insert_into(table).values(&validated.inner).execute(&mut conn)?;
```

### vld-tower

Universal [Tower](https://docs.rs/tower) middleware for JSON body validation.
Works with any Tower-compatible framework (Axum, Hyper, Tonic, Warp).

```toml
[dependencies]
vld-tower = "0.1"
```

```rust
use vld_tower::{ValidateJsonLayer, validated};
use tower::ServiceBuilder;

vld::schema! {
    #[derive(Debug, Clone)]
    pub struct CreateUser {
        pub name: String  => vld::string().min(2),
        pub email: String => vld::string().email(),
    }
}

// One layer covers all routes
let svc = ServiceBuilder::new()
    .layer(ValidateJsonLayer::<CreateUser>::new())
    .service_fn(handler);

// In handler — zero-cost extraction from extensions
let user: CreateUser = validated(&req);
```

### vld-config

Validate configuration files at load time. Supports [config-rs](https://docs.rs/config)
(TOML, YAML, JSON, ENV) and [figment](https://docs.rs/figment).

```toml
[dependencies]
vld = "0.1"
vld-config = "0.1"  # config-rs by default
# vld-config = { version = "0.1", features = ["figment"] }
```

```rust
use vld_config::prelude::*;

vld::schema! {
    #[derive(Debug)]
    pub struct Settings {
        pub host: String => vld::string().min(1),
        pub port: i64    => vld::number().int().min(1).max(65535),
    }
}

let config = config::Config::builder()
    .add_source(config::File::with_name("config"))
    .add_source(config::Environment::with_prefix("APP"))
    .build().unwrap();

let settings: Settings = from_config(&config).unwrap();
```

### vld-utoipa

Bridge between `vld` and [utoipa](https://docs.rs/utoipa). Define validation once, get
`ToSchema` for free — no need to duplicate schema definitions.
Works with both `vld::schema!` and `#[derive(Validate)]`.

```toml
[dependencies]
vld = { version = "0.1", features = ["openapi"] }
vld-utoipa = "0.1"
utoipa = "5"
```

```rust
use vld::prelude::*;
use vld_utoipa::impl_to_schema;

// Option A: schema! macro
vld::schema! {
    #[derive(Debug)]
    pub struct CreateUser {
        pub name: String => vld::string().min(2).max(100),
        pub email: String => vld::string().email(),
    }
}
impl_to_schema!(CreateUser);

// Option B: derive macro (requires features = ["derive", "openapi"])
#[derive(Debug, serde::Deserialize, vld::Validate)]
#[serde(rename_all = "camelCase")]
struct ApiRequest {
    #[vld(vld::string().min(1))]
    first_name: String,
    #[vld(vld::string().email())]
    email_address: String,
}
impl_to_schema!(ApiRequest);
// OpenAPI schema uses camelCase: "firstName", "emailAddress"
```

### vld-rocket

[Rocket](https://rocket.rs/) integration with validation extractors and JSON error catchers.

```toml
[dependencies]
vld-rocket = "0.1"
rocket = { version = "0.5", features = ["json"] }
```

```rust
use vld_rocket::prelude::*;

vld::schema! {
    #[derive(Debug, Clone)]
    pub struct CreateUser {
        pub name: String  => vld::string().min(2),
        pub email: String => vld::string().email(),
    }
}

#[rocket::post("/users", data = "<user>")]
fn create_user(user: VldJson<CreateUser>) -> rocket::serde::json::Json<serde_json::Value> {
    rocket::serde::json::Json(serde_json::json!({"name": user.name}))
}
```

### vld-poem

[Poem](https://docs.rs/poem) integration — extractors `VldJson`, `VldQuery`, `VldForm`.

```toml
[dependencies]
vld-poem = "0.1"
poem = "3"
```

```rust
use poem::handler;
use vld_poem::prelude::*;

vld::schema! {
    #[derive(Debug, Clone)]
    pub struct CreateUser {
        pub name: String  => vld::string().min(2),
        pub email: String => vld::string().email(),
    }
}

#[handler]
async fn create_user(user: VldJson<CreateUser>) -> poem::web::Json<serde_json::Value> {
    poem::web::Json(serde_json::json!({"name": user.name}))
}
```

### vld-warp

[Warp](https://docs.rs/warp) integration — filters `vld_json`, `vld_query` + `handle_rejection`.

```toml
[dependencies]
vld-warp = "0.1"
warp = "0.3"
```

```rust
use vld_warp::prelude::*;
use warp::Filter;

vld::schema! {
    #[derive(Debug, Clone)]
    pub struct CreateUser {
        pub name: String  => vld::string().min(2),
        pub email: String => vld::string().email(),
    }
}

let route = warp::post()
    .and(warp::path("users"))
    .and(vld_json::<CreateUser>())
    .map(|u: CreateUser| warp::reply::json(&serde_json::json!({"name": u.name})))
    .recover(handle_rejection);
```

### vld-sea

[SeaORM](https://www.sea-ql.org/SeaORM/) integration — validate `ActiveModel` before insert/update.

```toml
[dependencies]
vld-sea = "0.1"
sea-orm = "1"
```

```rust
use sea_orm::Set;
use vld_sea::prelude::*;

vld::schema! {
    #[derive(Debug, Clone)]
    pub struct UserInput {
        pub name: String  => vld::string().min(1).max(100),
        pub email: String => vld::string().email(),
    }
}

let am = user::ActiveModel {
    name: Set("Alice".to_owned()),
    email: Set("alice@example.com".to_owned()),
    ..Default::default()
};

// Validate before insert
vld_sea::validate_active::<UserInput, _>(&am)?;

// Or hook into before_save automatically:
// vld_sea::impl_vld_before_save!(ActiveModel, UserInput);
```

### vld-clap

[Clap](https://docs.rs/clap) integration — validate CLI arguments via `#[derive(Validate)]` directly on the struct.

```toml
[dependencies]
vld-clap = "0.1"
vld = { version = "0.1", features = ["derive"] }
clap = { version = "4", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
```

```rust
use clap::Parser;
use vld::Validate;
use vld_clap::prelude::*;

#[derive(Parser, Debug, serde::Serialize, Validate)]
struct Cli {
    #[arg(long)]
    #[vld(vld::string().email())]
    email: String,
    #[arg(long, default_value_t = 8080)]
    #[vld(vld::number().int().min(1).max(65535))]
    port: i64,
}

fn main() {
    let cli = Cli::parse();
    validate_or_exit(&cli);
    println!("email={}, port={}", cli.email, cli.port);
}
```

### vld-salvo

[Salvo](https://salvo.rs/) integration — extractors implement `Extractible` and work as
`#[handler]` function parameters, just like Salvo's built-in `JsonBody` or `PathParam`.

```toml
[dependencies]
vld-salvo = "0.1"
salvo = "0.89"
```

```rust
use salvo::prelude::*;
use vld_salvo::prelude::*;

vld::schema! {
    #[derive(Debug, Clone, serde::Serialize)]
    pub struct CreateUser {
        pub name: String  => vld::string().min(2),
        pub email: String => vld::string().email(),
    }
}

#[handler]
async fn create(body: VldJson<CreateUser>, res: &mut Response) {
    res.render(Json(serde_json::json!({"name": body.name})));
}
```

### vld-tauri

[Tauri](https://tauri.app/) IPC validation — commands, events, state, channels, plugin config.
**Zero dependency on `tauri`** — only `vld` + `serde` + `serde_json`.

```toml
[dependencies]
vld-tauri = "0.1"
tauri = "2"
```

```rust
use vld_tauri::prelude::*;

vld::schema! {
    #[derive(Debug, Clone, serde::Serialize)]
    pub struct CreateUser {
        pub name: String  => vld::string().min(2),
        pub email: String => vld::string().email(),
    }
}

// Pattern 1 — explicit
#[tauri::command]
fn create_user(payload: serde_json::Value) -> Result<String, VldTauriError> {
    let user = validate::<CreateUser>(payload)?;
    Ok(format!("Created {}", user.name))
}

// Pattern 2 — auto-validated
#[tauri::command]
fn create_user2(payload: VldPayload<CreateUser>) -> Result<String, VldTauriError> {
    Ok(format!("Created {}", payload.name))
}
```

### vld-fake

Generate **fake / test data** that satisfies `vld` validation schemas. Define rules once —
get instant, constraint-aware random data for tests, seed scripts, and demos.

```toml
[dependencies]
vld = { version = "0.1", features = ["openapi"] }
vld-fake = "0.1"
```

```rust
use vld::prelude::*;
use vld_fake::prelude::*;

vld::schema! {
    #[derive(Debug, Clone, serde::Serialize)]
    pub struct User {
        pub name:  String => vld::string().min(2).max(50),
        pub email: String => vld::string().email(),
        pub age:   i64    => vld::number().int().min(18).max(99),
    }
}

vld_fake::impl_fake!(User);

// Typed access — user.name, user.email, user.age
let user = User::fake();
println!("{} <{}> age={}", user.name, user.email, user.age);

// Multiple + reproducible
let users = User::fake_many(10);
let same  = User::fake_seeded(42);
```

### vld-ts

Generate TypeScript [Zod](https://zod.dev/) schemas from JSON Schema output produced by `vld`.
Useful for sharing validation contracts between Rust backend and TypeScript frontend.

```toml
[dependencies]
vld-ts = "0.1"
```

```rust
use vld_ts::generate_zod;

let json_schema = serde_json::json!({
    "type": "object",
    "required": ["name", "email"],
    "properties": {
        "name": { "type": "string", "minLength": 2 },
        "email": { "type": "string", "format": "email" }
    }
});
let ts_code = generate_zod("User", &json_schema);
// Output: export const UserSchema = z.object({ name: z.string().min(2), email: z.string().email() });
```

## License

MIT