laravel-rust 0.1.4

Laravel for Rust: a full-stack Rust web framework.
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
# Validation

- [Introduction](#introduction)
- [Validation quickstart](#validation-quickstart)
    - [Defining the input](#typed-input)
    - [Handling the request](#handling-the-request)
    - [Optional fields](#optional-fields)
    - [Fields a request may leave out](#fields-a-request-may-leave-out)
    - [Enum and ID fields](#enum-and-id-fields)
    - [Transforming input fields](#transforming-input-fields)
    - [Stopping on a field's first failure](#bail)
    - [Validation responses](#validation-responses)
- [Displaying errors and old input](#errors-and-old-input)
    - [Pages with several forms](#pages-with-several-forms)
- [Authorization and rules from the request](#request-hooks)
    - [Authorizing the request](#authorizing-the-request)
    - [Adding rules from the request](#adding-rules-from-the-request)
- [Validating in a handler](#validating-in-a-handler)
    - [Adding errors after validation](#adding-errors-after-validation)
- [Validating outside a request](#validating-outside-a-request)
- [Filters that ignore bad values](#lenient-input)
- [Available rules](#rules)
    - [Text and choices](#text-and-choices)
    - [Numbers](#numeric-bounds)
    - [Dates and times](#calendar-dates)
    - [Formats](#formats)
    - [Presence and acceptance](#presence-and-acceptance)
    - [Database records](#database-records)
    - [Passwords](#passwords)
    - [Current password](#current-password)
    - [Files](#files)
- [Conditional rules](#conditional-rules)
- [Nested objects](#nested-objects)
- [Validating lists](#validating-lists)
    - [Contains and distinct](#contains-and-distinct)
- [Custom messages and labels](#custom-messages-and-labels)
- [Custom rules](#custom-rules)
    - [Asynchronous checks](#async-rules)
- [Testing](#testing)

<a name="introduction"></a>
## Introduction

Validation lets you check the input your application receives before you use it. For example, a sign-up form should arrive with an email address, and an API client shouldn't be able to order `-3` of a product. With Laravel, you describe the input you expect as a Rust struct and put rules on its fields. Your handler only receives the struct once the input passes every rule. If it doesn't, Laravel redirects the user back to the form and shows them what needs fixing. An API client gets a JSON response that lists the errors instead.

Laravel includes rules for text, numbers, dates, formats such as email addresses, files, and database records, and you may write rules of your own. To see how the pieces fit together, let's look at a complete example of validating a form.

<a name="validation-quickstart"></a>
## Validation quickstart

For example, say your application lets users write blog posts. In `src/routes/web.rs`, one route shows the form for a new post, and another stores the post once the user submits the form:

```rust
use laravel::prelude::*;

use crate::http::handlers::posts;

pub fn routes(route: &mut Router) {
    route.get("/posts/create", posts::create);
    route.post("/posts", posts::store);
}
```

<a name="typed-input"></a>
### Defining the input

Next, in the module that holds your post handlers, describe the form's input as a struct. Mark the struct with `#[laravel::input(fills = Post)]`, which derives `Deserialize` and `Validate` for it and lets you save it to a `Post`. Then put each field's rules in a `#[validate(...)]` attribute:

```rust
use laravel::prelude::*;

use crate::models::Post;

#[laravel::input(fills = Post)]
#[validate(anyone)]
pub struct StorePost {
    #[validate(required, max_length(255), unique(Post::title))]
    title: String,
    #[validate(required)]
    body: String,
}
```

Laravel checks each field's rules in the order you write them. To learn more about the rules you may use, check out the [available rules](#rules).

`#[validate(anyone)]` says that anyone who can reach the route may submit the form. Every type you validate from a request must say who may submit it. So a handler that validates a type without `anyone`, `authenticated`, or an [`authorize` function](#authorizing-the-request) doesn't compile. To keep the focus on the rules, the rule examples later on this page leave this attribute out, but your own types need it.

A `String` field accepts only text, and a number field such as `u32` accepts only numbers that fit it, so you don't need rules for the type.

<a name="handling-the-request"></a>
### Handling the request

Now take a `Valid<T>` argument in your `store` handler. It must be the handler's last argument, because it reads the request's body:

```rust
use laravel::model::create;
use laravel::prelude::*;

use crate::models::Post;

pub async fn store(Valid(form): Valid<StorePost>) -> laravel::Result<Redirect> {
    let post = create!(Post { ..form }).await?;

    Ok(redirect!(show, post.id))
}
```

Your `store` handler only runs when the input fits the struct and passes every rule. If it doesn't, Laravel sends the user back to the form with the errors, and your handler never runs.

<a name="saving-the-input-to-a-model"></a>
`fills = Post` makes `StorePost` a fill struct for the `Post` model. Each of its fields fills the `Post` column of the same name, and `..form` at the end of `create!` copies the fields into the new post. A fill struct also lists the only columns a request may write. Laravel ignores any submitted field that the struct doesn't declare, so a user can't add `is_admin=1` to the form and change a column you never showed them. To learn more, check out the models guide's section on [fill structs](models.md#fill-structs).

<a name="reading-the-request-with-the-input"></a>
`Valid<T>` and `Request` both read the request's body, so a handler can't take both. If your handler needs the request too, take a `ValidRequest<T>` as its last argument instead. It validates `T` as `Valid<T>` does, and its `into_parts` method returns the input and the request. For example, if your `posts` table has an `ip_address` column for moderating spam, this handler records the address each post came from:

```rust
use laravel::validation::ValidRequest;

pub async fn store(input: ValidRequest<StorePost>) -> laravel::Result<Redirect> {
    let (form, request) = input.into_parts();

    let post = create!(Post { ip_address: request.ip().to_string(), ..form }).await?;

    Ok(redirect!(show, post.id))
}
```

If you only need to read the input, you don't need `into_parts`. You may read the input's fields through the `ValidRequest` itself, as in `input.title`, and its `request` method returns the request.

<a name="optional-fields"></a>
### Optional fields

If the user may leave a field empty, such as the date a post should be published, declare the field as an `Option`. Laravel's default `TrimStrings` and `ConvertEmptyStringsToNull` [middleware](middleware.md) turn an empty text input into `null` before validation runs, and an `Option` field receives `null` as `None`. If the user does fill in the field, the field's other rules still check the value:

```rust
#[laravel::input]
pub struct StorePost {
    #[validate(required, max_length(255))]
    title: String,
    #[validate(date)]
    publish_on: Option<laravel::time::civil::Date>,
}
```

Ordinary rules, such as `max_length` and `date`, skip missing fields and blank strings. They skip `null` only on nullable fields, such as an `Option`. Add `required` when an empty value should fail.

<a name="fields-a-request-may-leave-out"></a>
### Fields a request may leave out

An `Option` field can't tell a field the request left out from one it sent empty. An HTML form sends every field, so that's usually fine. A JSON `PATCH` request, or an Inertia form that sends only what changed, leaves out the fields the user didn't touch. There, a missing field typically means "keep the current value", and `null` means "clear it".

Declare those fields as `Sometimes<T>`. A field the request leaves out is `Sometimes::Missing`, and validation skips all of its rules, `required` included. A field the request sends is `Sometimes::Present`, and its rules run as usual:

```rust
use laravel::validation::Sometimes;

#[laravel::input]
#[validate(authenticated)]
pub struct EditProfile {
    #[validate(required, max_length(255))]
    pub name: Sometimes<String>,
    #[validate(max_length(1000))]
    pub bio: Sometimes<Option<String>>,
}
```

| The request | `name` | `bio` |
| --- | --- | --- |
| Leaves out both fields | `Missing` | `Missing` |
| Sends `name` as `"Taylor"` | `Present("Taylor")` | `Missing` |
| Sends `bio` as `null` or blank | `Missing` | `Present(None)` |
| Sends `name` as `null` or blank | Fails: "The name field is required." | `Missing` |

So `required` on a `Sometimes` field means "not empty, if sent". A `Sometimes<String>` field that the request sends must hold text, even without `required`. To let a sent field be empty, declare it `Sometimes<Option<String>>`, as `bio` does.

In the handler, match on the field or use its helpers. `present()` returns the sent value as an `Option`, `is_missing()` says whether the request left the field out, and `is_null()` says whether a `Sometimes<Option<T>>` field was sent empty. When you save a [fill struct](#saving-the-input-to-a-model) to a model, Laravel skips every `Missing` field, so those columns keep their current values. To learn more, check out the models guide's section on [updating only the fields a request sends](models.md#updating-only-the-fields-a-request-sends).

<a name="enum-and-id-fields"></a>
### Enum and ID fields

A form often offers a fixed set of choices, such as whether a new post is a draft or published right away. To accept one of those choices, declare the field as your own enum and derive `Enum` for it, as you would for an [enum column](models.md#enum-columns). The field then accepts only the variants' Serde names, so with `#[serde(rename_all = "snake_case")]`, `visibility=published` decodes to `Visibility::Published` and `visibility=archived` fails validation:

```rust
use laravel::prelude::*;

#[derive(Clone, Copy, Debug, Serialize, Deserialize, Enum)]
#[serde(rename_all = "snake_case")]
pub enum Visibility {
    Draft,
    Published,
}

#[laravel::input]
pub struct StorePost {
    #[validate(required, max_length(255))]
    title: String,
    visibility: Visibility,
}
```

Rules such as `one_of` and `distinct` compare a variant by its Serde name, so write `one_of("draft")` rather than the variant's Rust name.

Some applications wrap IDs in their own types, so a `CategoryId` can't be passed where a `UserId` belongs. Derive `Newtype` for such a wrapper, and the field accepts and validates the same input as the type it wraps:

```rust
#[derive(Clone, Copy, Debug, Deserialize, Newtype)]
pub struct CategoryId(i64);

#[laravel::input]
pub struct StorePost {
    #[validate(required, max_length(255))]
    title: String,
    #[validate(min_value(1))]
    category_id: CategoryId,
}
```

<a name="transforming-input-fields"></a>
### Transforming input fields

Sometimes you'll want to normalize a field's casing before you validate or store it, such as lowercasing email addresses so database unique indexes match regardless of how the user typed them, or uppercasing country and coupon codes. You may add `#[transform(lowercase)]` or `#[transform(uppercase)]` to any string field on an input or query struct:

```rust
use laravel::prelude::*;

use crate::models::User;

#[laravel::input(fills = User)]
#[validate(anyone)]
pub struct RegisterUser {
    #[validate(required, max_length(255))]
    name: String,
    #[transform(lowercase)]
    #[validate(required, email, unique(User::email))]
    email: String,
    #[transform(uppercase)]
    #[validate(required, min_length(2), max_length(2))]
    country: String,
}
```

Laravel runs `#[transform(..)]` as soon as the request binds into the struct, before validation rules, dynamic `rules` hooks, and your handler see the value. If a user submits `Taylor@Example.com`, the `unique` rule queries the database for `taylor@example.com`, and your handler receives `taylor@example.com`. When a browser form fails validation, old input keeps what the user originally typed.

`#[transform(..)]` works on `String` fields, `Newtype` wrappers around `String`, and `Option`, `Sometimes`, `Box`, `Vec`, set, and map fields that hold strings. It applies across `Valid<T>`, `ValidRequest<T>`, `request.parse()`, `request.json()`, and `Query<T>`. To transform a field across every request regardless of which struct binds it, use a middleware with [`transform_input`](requests.md#transforming-input) instead.

<a name="bail"></a>
### Stopping on a field's first failure

Sometimes you'll want to stop checking a field after its first failure, such as to skip a database query for a title that's already too long. To do so, add `bail` to the field's rules. In this example, if the title is longer than 255 characters, the `unique` rule never queries the database:

```rust
#[validate(bail, required, max_length(255), unique(Post::title))]
title: String,
```

`bail` stops only its own field. Other fields keep validating, so the user still sees every field that needs fixing. When a [presence rule](#presence-and-acceptance) such as `required` fails, Laravel skips the rest of that field's rules even without `bail`.

<a name="validation-responses"></a>
### Validation responses

When validation fails, Laravel responds based on the kind of request:

- A browser form on a route in the `web` group gets a redirect back to the previous page. The errors and the submitted input go in the session, so the form can [show them](#errors-and-old-input).
- An [Inertia](inertia.md#validation-errors) form gets the same redirect, and the page receives the errors in its `errors` prop.
- A request that expects JSON, or a route in the `api` group, gets a `422 Unprocessable Content` with the errors as JSON.
- A browser request to a route without a session can't carry errors through a redirect, so it gets the `422` error page.

The JSON response has a `message` with the first error and a count of the rest, and an `errors` object with each field's messages. Nested fields use dots in their keys:

```json
{
    "message": "The title field is required. (and 1 more error)",
    "errors": {
        "title": ["The title field is required."],
        "author.name": ["The author.name field is required."]
    }
}
```

<a name="errors-and-old-input"></a>
## Displaying errors and old input

When validation fails on a web route, Laravel redirects the user back with the validation errors so your page can display them next to each field or in a summary above the form.

#### Inertia

If your application uses [Inertia](inertia.md#validation-errors), Laravel populates the page's `errors` prop automatically while keeping the user's input intact. Inertia's `<Form>` component exposes `errors` through its render prop, so you can show an individual field's message or loop through every error on the form:

```tsx
import { Form } from "@inertiajs/react";

export default function CreatePost() {
    return (
        <Form action="/posts" method="post">
            {({ errors }) => (
                <>
                    {Object.keys(errors).length > 0 && (
                        <ul className="errors">
                            {Object.entries(errors).map(([field, message]) => (
                                <li key={field}>{message}</li>
                            ))}
                        </ul>
                    )}

                    <label htmlFor="title">Title</label>
                    <input id="title" name="title" />
                    {errors.title && <p className="error">{errors.title}</p>}
                </>
            )}
        </Form>
    );
}
```

#### MiniJinja

When rendering server-side templates with MiniJinja, Laravel flashes the errors and the submitted input to the session for the next request. Use `error` to read a field's first error and `old` to fill the field back in with what the user typed, passing a default value as the second argument for the initial render:

```html
<!-- resources/views/posts/create.html -->

<label for="title">Title</label>
<input id="title" name="title" value="{{ old('title', '') }}">

{% if error('title') %}
    <p class="error">{{ error('title') }}</p>
{% endif %}
```

Your views also receive every error in an `errors` map, keyed by field, so `errors.title` holds all of the title's messages. To list every message above the form, loop over the map:

```html
{% if errors %}
    <ul class="errors">
        {% for field, messages in errors|items %}
            {% for message in messages %}
                <li>{{ message }}</li>
            {% endfor %}
        {% endfor %}
    </ul>
{% endif %}
```

To see a complete form that shows its errors, check out the templates guide's section on [validation errors and old input](templates.md#validation-errors-and-old-input).

If you need old input in a handler, [`request.old::<String>("title")`](requests.md#old-input) returns the submitted value as the type you name. It accepts dotted paths, such as `author.name`, and returns `None` when the field wasn't submitted or isn't that type.

Old input never includes passwords or uploaded files, so the user enters those again. Laravel leaves out every [`Password`](hashing.md#password-fields) field of the validated type, and any field named `password`, `password_confirmation`, or `current_password`. To keep other fields out of the session, list them with [`dont_flash`](errors.md#keeping-input-out-of-old-input).

<a name="pages-with-several-forms"></a>
### Pages with several forms

When a page has two forms with the same field, such as a login form and a registration form that both have an `email` field, name each form on its input type to keep its errors apart:

```rust
use laravel::hash::Password;

#[laravel::input]
#[validate(anyone, form = "login")]
pub struct Login {
    #[validate(required, email)]
    email: String,
    #[validate(required)]
    password: Password,
}
```

#### Inertia

Inertia pages receive a named form's errors under its name, such as `errors.login.email`. Pass `errorBag` to `<Form>` so its `errors` render prop is scoped to that form automatically:

```tsx
import { Form } from "@inertiajs/react";

export default function LoginForm() {
    return (
        <Form action="/login" method="post" errorBag="login">
            {({ errors }) => (
                <>
                    {Object.keys(errors).length > 0 && (
                        <ul className="errors">
                            {Object.entries(errors).map(([field, message]) => (
                                <li key={field}>{message}</li>
                            ))}
                        </ul>
                    )}

                    <label htmlFor="email">Email</label>
                    <input id="email" name="email" type="email" />
                    {errors.email && <p className="error">{errors.email}</p>}
                </>
            )}
        </Form>
    );
}
```

#### MiniJinja

In a MiniJinja template, pass the form's name to `error` to read that form's messages. The `errors` map only holds the errors of forms without a name:

```html
{% if error("email", form="login") %}
    <p class="error">{{ error("email", form="login") }}</p>
{% endif %}
```

Every named form's errors are also in `form_errors`, keyed by form name. Use `form_errors.login` to list all errors for the `login` form, or `form_errors.login.email` to list one field's messages:

```html
{% if form_errors.login %}
    <ul class="errors">
        {% for field, messages in form_errors.login|items %}
            {% for message in messages %}
                <li>{{ message }}</li>
            {% endfor %}
        {% endfor %}
    </ul>
{% endif %}
```

#### Scoping handler errors

Errors that your handler returns after validation, such as with [`invalid!`](#adding-errors-after-validation), are automatically scoped to the same named form. For example, because this handler accepts `Valid<Login>`, when `auth.attempt` rejects invalid credentials, the error appears under `errors.login.email` in Inertia pages and `error("email", form="login")` in MiniJinja templates:

```rust
use laravel::auth::Auth;
use laravel::prelude::*;

pub async fn login(
    auth: Auth<User>,
    Valid(form): Valid<Login>,
) -> laravel::Result<Redirect> {
    auth.attempt(&form.email, &form.password).await?;

    Ok(Redirect::intended(dashboard::show, ()))
}
```

When several forms on a page submit the same input type, such as a reply form under each comment, name each form with a hidden `_form` field instead, as in `<input type="hidden" name="_form" value="reply-7">`. If a request sends a `_form` field for a type that also has a name, Laravel uses the `_form` field's name.

<a name="request-hooks"></a>
## Authorization and rules from the request

Sometimes a form needs more than rules. For example, a form that renames a team should check that the user may rename it, and a rule might depend on who's asking. To keep that logic next to the form's rules, rather than in every handler that takes the form, implement `ValidatesRequest` on the input type.

`ValidatesRequest` has two functions. `authorize` decides who may submit the type, and `rules` adds rules that depend on the request. `Valid<T>` runs both before your handler. Say each `User` has an `is_admin` flag and an `is_premium` plan. Only admins may rename their team, and premium teams get longer names:

```rust
use laravel::prelude::*;
use laravel::validation::{Rule, Rules, ValidatesRequest};

#[laravel::input]
pub struct UpdateTeam {
    #[validate(required, max_length(255))]
    name: String,
}

impl ValidatesRequest for UpdateTeam {
    async fn authorize(request: &Request) -> laravel::Result<bool> {
        let admin = request
            .user::<User>()
            .await?
            .is_some_and(|user| user.is_admin);

        Ok(admin)
    }

    async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
        let premium = request
            .user::<User>()
            .await?
            .is_some_and(|user| user.is_premium);

        Ok(rules.field("name", [Rule::max_length(if premium { 255 } else { 50 })]))
    }
}

pub async fn update(Valid(team): Valid<UpdateTeam>) -> laravel::Result<Redirect> {
    // Only admins get here, with a name that fits their plan...

    Ok(Redirect::back())
}
```

`authorize` is required, and `rules` is optional. If you leave out `rules`, Laravel validates with the rules declared on the struct's fields. When you do write `rules`, its `rules` argument already holds the rules declared on the struct. Calling `rules.field("name", ..)` adds more rules to the `name` field rather than replacing the ones it has. So in this example, a team's name must still pass `required` and `max_length(255)` from the struct, and then the limit for the user's plan.

Only the struct your handler validates needs `ValidatesRequest`. A [nested struct](#nested-objects) or [list item](#validating-lists) always uses the rules declared on its own fields. For example, if the team form also takes the team's billing address, only `UpdateTeam` implements `ValidatesRequest`. Laravel checks `billing_address` with the rules on `Address`'s fields:

```rust
#[laravel::input]
pub struct UpdateTeam {
    #[validate(required, max_length(255))]
    name: String,
    billing_address: Address,
}

#[laravel::input]
pub struct Address {
    #[validate(required, max_length(255))]
    street: String,
    #[validate(required)]
    city: String,
}
```

<a name="authorizing-the-request"></a>
### Authorizing the request

`authorize` runs before validation. If it returns `false`, the request fails with a `403` and the message "This action is unauthorized.", and Laravel doesn't validate the input.

To tell the user why you rejected the request, abort with your own message instead of returning `false`:

```rust
async fn authorize(request: &Request) -> laravel::Result<bool> {
    let admin = request
        .user::<User>()
        .await?
        .is_some_and(|user| user.is_admin);

    if !admin {
        laravel::abort!(403, "Only team admins can rename a team.");
    }

    Ok(true)
}
```

You may skip writing `authorize` for the two most common answers:

- `#[validate(anyone)]` lets anyone submit the form, such as a contact form or a login form.
- `#[validate(authenticated)]` lets any logged-in user submit it, such as a change-password form. A guest gets the same response as from the [`Authenticate`](authentication.md#redirecting-guests) middleware: a redirect to the login page, or a `401` for a request that expects JSON.

```rust
#[laravel::input]
#[validate(authenticated)]
pub struct UpdateProfile {
    #[validate(required, max_length(255))]
    name: String,
}
```

If a type needs a `rules` function too, implement `ValidatesRequest` yourself instead of using these attributes. For a form that any logged-in user may submit, have `authorize` return `request.authenticated()`:

```rust
impl ValidatesRequest for UpdateProfile {
    async fn authorize(request: &Request) -> laravel::Result<bool> {
        Ok(request.authenticated().await?)
    }

    async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
        // Add rules that depend on the request...

        Ok(rules)
    }
}
```

When `authorize` returns `false`, a guest gets a `403` rather than a redirect to your login page. If guests should be sent to log in, attach the [`Authenticate`](authentication.md#protecting-routes) middleware to the form's route.

<a name="authorizing-with-a-policy"></a>
#### Authorizing with a policy

When a [policy](authorization.md) decides who may submit a form, name the policy method instead of writing `authorize`. For each record the method takes, pass `route("...")` with the route parameter that names the record:

```rust
use crate::policies::PostPolicy;

#[laravel::input]
#[validate(authorize(PostPolicy::update, route("post")))]
pub struct UpdatePost {
    #[validate(required, max_length(255))]
    title: String,
}
```

On a route such as `PUT /posts/{post}`, Laravel finds the post and checks `PostPolicy::update` for the current user. A denial gets the policy's response, such as a `403` with its message. For a method without a record, leave out the arguments, as in `authorize(PostPolicy::create)`. To learn more, check out the authorization guide's section on [authorizing a form](authorization.md#authorizing-a-form).

<a name="adding-rules-from-the-request"></a>
### Adding rules from the request

Sometimes a rule needs a record that the URL names. For example, say customers order a product at `POST /products/{product}/orders`, and each `Product` has a `stock` column. An order shouldn't ask for more than the product has in stock. To find the product in your `rules` function, call `request.model` with the route parameter's name:

```rust
use laravel::prelude::*;
use laravel::validation::{Rule, Rules, ValidatesRequest};

use crate::models::Product;

#[laravel::input]
pub struct StoreOrder {
    #[validate(required, min_value(1))]
    quantity: u32,
}

impl ValidatesRequest for StoreOrder {
    async fn authorize(request: &Request) -> laravel::Result<bool> {
        Ok(request.authenticated().await?)
    }

    async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
        let product: Product = request.model("product").await?;

        Ok(rules.field("quantity", [Rule::max_value(product.stock)]))
    }
}
```

If no product has the ID in the URL, the request gets a `404`. Laravel finds the product once per request, so your handler may also take a `product: Product` argument without another query.

Because Laravel decodes the input into your struct before calling `rules`, you may also inspect fields on `self` when choosing which rules to add. For example, a webhook form might require an HTTPS URL for HTTP webhooks and an identifier for queue webhooks:

```rust
use laravel::prelude::*;
use laravel::validation::{Rule, Rules, ValidatesRequest};

#[laravel::input]
pub struct StoreWebhook {
    #[validate(required, one_of("http", "queue"))]
    kind: String,
    #[validate(required)]
    target: String,
}

impl ValidatesRequest for StoreWebhook {
    async fn authorize(request: &Request) -> laravel::Result<bool> {
        Ok(request.authenticated().await?)
    }

    async fn rules(&self, _request: &Request, rules: Rules) -> laravel::Result<Rules> {
        if self.kind == "http" {
            Ok(rules.field("target", [Rule::url(["https"])]))
        } else {
            Ok(rules.field("target", [Rule::alpha_dash()]))
        }
    }
}
```

<a name="validating-in-a-handler"></a>
## Validating in a handler

Most handlers take `Valid<T>`. If you'd like to decide what happens when validation fails, take the `Request` instead and call `request.validate::<T>()`. If you use `?` on its result, Laravel redirects a browser back to the form with the errors and the user's input, and gives an API client a `422` JSON response that lists the errors:

```rust
use laravel::prelude::*;

pub async fn store(request: Request) -> laravel::Result<Redirect> {
    let form: StorePost = request.validate().await?;

    // Store the post...

    Ok(Redirect::back())
}
```

To send your own response instead, match on the `ValidationError`. For example, on a page that swaps the form in place without reloading, this handler returns only the form's template fragment. The fragment shows the errors and keeps what the user typed through `with_input`, and the response has a `422` status:

```rust
use laravel::prelude::*;
use laravel::validation::ValidationError;

pub async fn store(request: Request) -> laravel::Result<Response> {
    let form = match request.validate::<StorePost>().await {
        Ok(form) => form,
        Err(ValidationError::Invalid(errors)) => {
            return Ok(view("posts.create", data! {})
                .with_errors(errors)
                .with_input(&request)
                .fragment("form")
                .with_status(StatusCode::UNPROCESSABLE_ENTITY)
                .into_response());
        }
        Err(ValidationError::Failed(error)) => return Err(error),
    };

    // Store the post...

    Ok(redirect!(index).into_response())
}
```

`ValidationError::Invalid` holds the field errors. `ValidationError::Failed` holds an error that stopped validation, such as a database outage in a [`unique` rule](#database-records). Return it with `?` so that your error handler reports it.

<a name="adding-errors-after-validation"></a>
### Adding errors after validation

Rules check one field at a time, so they can't express every piece of your application's business logic. For example, whether a hotel room is free depends on both of the dates a guest picked and on the bookings already in your database.

For checks like that, validate what the rules can, then do the rest in your handler. If the input fails your check, return an error for the field with `invalid!`. The user gets the same response as a failed validation: a redirect back to the form with the errors and the user's input, or a `422` JSON response for an API client:

```rust
use laravel::prelude::*;
use laravel::time::civil::Date;
use laravel::validation::invalid;

use crate::models::{Booking, Room};

#[laravel::input]
#[validate(authenticated)]
pub struct StoreBooking {
    #[validate(required, exists(Room::id))]
    room_id: i64,
    #[validate(required, label = "arrival date")]
    starts_on: Date,
    #[validate(required, after(starts_on), label = "departure date")]
    ends_on: Date,
}

pub async fn store(Valid(form): Valid<StoreBooking>) -> laravel::Result<Redirect> {
    let taken = Booking::query()
        .filter(Booking::room_id.eq(form.room_id))
        .filter(Booking::starts_on.lt(form.ends_on))
        .filter(Booking::ends_on.gt(form.starts_on))
        .exists()
        .await?;

    if taken {
        invalid!(starts_on => "The room is already booked for some of those dates.");
    }

    // Store the booking...

    Ok(redirect!(bookings::index))
}
```

To add an error to a nested field with `invalid!`, write the field's path in "dot" notation, either as a quoted literal such as `"items.0.quantity"` or a string expression such as `format!("items.{index}.quantity")`. To give a field several messages, pass a list:

```rust
invalid!(
    password => ["The password is too common.", "The password appeared in a data breach."],
    "items.0.quantity" => "Only 3 are left in stock.",
    format!("members.{index}.user_id") => "This user is already a member.",
);
```

If you'd like to collect errors as you go, build an `InvalidInput` and call `add` with a field's name and a message for each problem you find. When you return the errors from a handler, Laravel redirects the user back to the form with every error you added, or gives an API client a `422` JSON response that lists them.

For example, this handler checks each item of an order against the stock of its product:

```rust
use laravel::validation::InvalidInput;

use crate::models::Product;

pub async fn store(Valid(order): Valid<StoreOrder>) -> laravel::Result<Redirect> {
    let mut errors = InvalidInput::new();

    for (index, item) in order.items.iter().enumerate() {
        let product = Product::find_or_fail(item.product_id).await?;

        if i64::from(item.quantity) > product.stock {
            errors.add(
                format!("items.{index}.quantity"),
                format!("Only {} are left in stock.", product.stock),
            );
        }
    }

    if !errors.is_empty() {
        return Err(errors.into());
    }

    // Store the order...

    Ok(redirect!(orders::index))
}
```

To send the user somewhere other than back to the form, such as to their cart, redirect with the errors yourself:

```rust
return Ok(redirect!(cart::show).with_errors(errors));
```

On a page with [several forms](#pages-with-several-forms), errors you add are automatically scoped to the same form as validation errors. Laravel uses the submitted `_form` name when present, or falls back to the type's `#[validate(form = "...")]` name. This applies whether you return the errors directly or attach them to a redirect or view. To target a different form instead, call `errors.for_form("register")`.

<a name="validating-outside-a-request"></a>
## Validating outside a request

Sometimes you'll need to check data that didn't come from a request, such as each row of a CSV file that a console command imports. Derive `Validate` on a struct to declare the row's rules, build the struct, and call `validate`:

```rust
use laravel::validation::{Validate, ValidationError};

#[derive(Validate)]
struct ImportedPost {
    #[validate(required, max_length(255))]
    title: String,
    #[validate(required)]
    body: String,
}

pub async fn import_row(row: &[String]) -> laravel::Result<()> {
    let post = ImportedPost {
        title: row[0].clone(),
        body: row[1].clone(),
    };

    match post.validate().await {
        Ok(()) => {
            // Store the post...
        }
        Err(ValidationError::Invalid(errors)) => {
            for (field, messages) in errors.errors() {
                for message in messages {
                    println!("{field}: {message}");
                }
            }
        }
        Err(ValidationError::Failed(error)) => return Err(error),
    }

    Ok(())
}
```

`validate` checks the struct's fields as any other `Validate` struct does. Inside a handler returning `laravel::Result`, you may propagate `post.validate().await?` directly with `?`, and Laravel turns `ValidationError::Invalid` into a `422` JSON response for API requests or a redirect back with the errors for browser requests. Derive `Fill` alongside `Validate` with `#[fills(Post)]` to pass the validated struct straight to `create!` or `update!`:

```rust
use laravel::model::{Fill, create};
use laravel::prelude::*;
use laravel::validation::Validate;

use crate::models::{Post, User};

#[derive(Validate, Fill)]
#[fills(Post)]
struct ImportedPost {
    #[validate(required, max_length(255))]
    title: String,
    #[validate(required)]
    body: String,
}

pub async fn import(Authenticated(user): Authenticated<User>) -> laravel::Result<Redirect> {
    let input = ImportedPost {
        title: "Imported post".into(),
        body: "Post contents...".into(),
    };

    input.validate().await?;

    let post = create!(Post { user: &user, ..input }).await?;

    Ok(redirect!(posts::show, &post))
}
```

To learn more about `Fill` structs, check out the models guide's section on [fill structs](models.md#fill-structs).

<a name="lenient-input"></a>
## Filters that ignore bad values

A list page often reads its filters from the query string, as in `/issues?priority=high&assignee=7`. Users bookmark and share those URLs, so a filter may arrive with a value that's no longer valid. Redirecting back doesn't help a user who opened a bookmark, because there's no previous page with a form to show the error on. It's better to drop the bad filter and show the list.

Mark your filter struct with `#[laravel::query]` and extract it with `Query<T>`. Every field with a fallback (`Option<T>`, `#[default]`, or `#[default = value]`) is lenient: if a parameter is blank, doesn't decode (such as an unknown enum value or `assignee=abc` for an `i64`), or fails its `#[validate(..)]` rules, Laravel drops that field and uses its fallback while keeping the rest:

```rust
use laravel::inertia::{self, Page, props};
use laravel::prelude::*;

#[derive(Deserialize, Serialize, Enum)]
#[serde(rename_all = "snake_case")]
pub enum Priority {
    Low,
    High,
}

#[laravel::query]
#[derive(Serialize)]
pub struct IssueFilters {
    priority: Option<Priority>,
    assignee: Option<i64>,
    #[default]
    #[validate(max_length(100))]
    q: String,
    #[default = 1]
    #[validate(min_value(1))]
    page: u32,
    #[default]
    labels: Vec<i64>,
}

pub async fn index(Query(filters): Query<IssueFilters>) -> Page {
    // Query the issues that match the filters...

    inertia::render("Issues/Index", props! { filters })
}
```

`/issues?priority=bogus&assignee=7&page=0` reaches the handler with `priority` as `None`, `assignee` as `Some(7)`, and `page` as `1`. Fields without `Option` or `#[default]` stay required and respond with `400 Bad Request` when missing or invalid. To learn more, check out [query string input](requests.md#query-string-input).

The handler passes the filters back to the page, so the page can show which ones are applied. Inertia sends props to the browser as JSON, so `IssueFilters` and `Priority` also derive `Serialize`.

<a name="rules"></a>
## Available rules

The sections below list every rule Laravel includes, grouped by the kind of value each rule checks. Each section's table shows the rules as you'd write them in a field's `#[validate(...)]` attribute, which is where you'll usually put them:

```rust
#[laravel::input]
pub struct StorePost {
    #[validate(required, max_length(100))]
    title: String,
    #[validate(required, one_of("draft", "published"))]
    status: String,
}
```

When you add rules in code instead, such as in a [`rules` function](#adding-rules-from-the-request), each rule has a `Rule` constructor with the same name. A rule that takes several values, such as `one_of`, takes them as an array:

```rust
rules
    .field("title", [Rule::required(), Rule::max_length(100)])
    .field("status", [Rule::required(), Rule::one_of(["draft", "published"])])
```

Most rules skip missing fields and blank strings. Add `required` to a field that must have a value.

<a name="text-and-choices"></a>
### Text and choices

| Attribute | Passes when the value is |
| --- | --- |
| `string` | Text. `String` fields have this rule already |
| `min_length(3)` | Text of at least 3 characters |
| `max_length(255)` | Text of at most 255 characters |
| `one_of("draft", "published")` | One of the choices |
| `not_one_of("admin", "root")` | None of the choices |
| `confirmed` | The same as the `<name>_confirmation` field, such as `password_confirmation` |
| `same(email)` | The same as another field |
| `different(username)` | Different from another field |
| `alpha` | Letters only, from any language, such as `José` |
| `alpha_num` | Letters from any language, and numbers |
| `alpha_dash` | Letters from any language, numbers, dashes, and underscores |
| `ascii` | ASCII characters only. Add it to `alpha_dash` for a username such as `jane_doe` |
| `lowercase` | Already lowercase |
| `uppercase` | Already uppercase |
| `starts_with("+1", "+44")` | Starts with one of the prefixes |
| `ends_with(".jpg", ".png")` | Ends with one of the suffixes |
| `doesnt_start_with("_")` | Starts with none of the prefixes |
| `doesnt_end_with(".exe")` | Ends with none of the suffixes |
| `digits(4)` | Exactly 4 digits |
| `digits_between(4, 6)` | Between 4 and 6 digits |
| `min_digits(4)` | At least 4 digits |
| `max_digits(6)` | At most 6 digits |

Lengths count characters, not bytes, and limits are inclusive.

<a name="numeric-bounds"></a>
### Numbers

| Attribute | Passes when the value is |
| --- | --- |
| `min_value(1)` | At least 1 |
| `max_value(100)` | At most 100 |
| `between(0.0, 5.0)` | From 0 to 5, inclusive |
| `gt(minimum)` | Greater than another field |
| `gte(minimum)` | Greater than or equal to another field |
| `lt(price)` | Less than another field |
| `lte(price)` | Less than or equal to another field |
| `decimal(2)` | A number with exactly 2 decimal places |
| `decimal(2, 4)` | A number with 2 to 4 decimal places |
| `multiple_of(12)` | A multiple of 12 |

These rules compare numbers, not text lengths, and they accept numbers sent as text, such as a form's `"12.50"`. For example, this form accepts an order of 1 to 100 items, and an optional rating from 0 to 5:

```rust
#[laravel::input]
pub struct StoreOrder {
    #[validate(required, min_value(1), max_value(100))]
    quantity: u32,
    #[validate(between(0.0, 5.0))]
    rating: Option<f64>,
}
```

<a name="comparing-numeric-fields"></a>
`gt`, `gte`, `lt`, and `lte` always name another field, never a literal number. Use `min_value`, `max_value`, or `between` for a fixed limit. A comparison fails when the other field is missing, so add `required` to that field if clients must send it:

```rust
#[laravel::input]
pub struct PriceRange {
    #[validate(required, min_value(0), label = "minimum price")]
    minimum: u64,
    #[validate(required, gte(minimum), label = "maximum price")]
    maximum: u64,
}
```

<a name="decimal-places-and-multiples"></a>
#### Decimal places and multiples

`decimal` counts the decimal places the user wrote. With `decimal(2)`, `"12.50"` passes, while `"12"`, `"12.5"`, and `"12.500"` fail. Add `min_value(0)` if a price can't be negative:

```rust
use laravel::numeric::Decimal;

#[laravel::input]
pub struct StoreProduct {
    #[validate(required, decimal(2), min_value(0))]
    price: Decimal,
    #[validate(required, multiple_of(12))]
    quantity: u32,
}
```

For money and other exact amounts, use `laravel::numeric::Decimal` rather than `f64`. `Valid<T>` decodes form text and JSON numbers into a `Decimal` without rounding them, and [databases](database.md#decimals) store it exactly. An `f64` field receives an approximate value.

<a name="calendar-dates"></a>
### Dates and times

| Attribute | Passes when the value is |
| --- | --- |
| `date` | A real calendar date, such as `2024-02-29` |
| `datetime` | A timestamp with a UTC offset, such as `2024-02-29T09:30:00Z` |
| `date_format("%d/%m/%Y")` | Text in one of the formats |
| `timezone` | A time zone name, such as `America/Chicago` |
| `after(starts_on)` | After another field's date or time |
| `after_or_equal(starts_on)` | On or after another field's date or time |
| `before(ends_on)` | Before another field's date or time |
| `before_or_equal(ends_on)` | On or before another field's date or time |
| `date_equals(starts_on)` | The same as another field's date or time |
| `after_today` | A date after today |
| `today_or_after` | Today or a later date |
| `before_today` | A date before today |
| `today_or_before` | Today or an earlier date |

An HTML `<input type="date">` submits a date such as `2024-02-29`. Declare the field as a [`laravel::time::civil::Date`](time.md), and Laravel checks that the value is a real calendar date, as the `date` rule does. Your handler then receives a typed date:

```rust
use laravel::time::civil::Date;

#[laravel::input]
pub struct StoreBooking {
    #[validate(required, today_or_after, label = "arrival date")]
    starts_on: Date,
    #[validate(required, after_or_equal(starts_on), label = "departure date")]
    ends_on: Date,
}
```

In this example, a guest may book a stay that starts today or later, and ends on or after the day it starts. Laravel compares dates with today's date in UTC, the time zone its clock uses, so today may already be tomorrow for a user in another part of the world.

`timezone` accepts a name from the IANA time zone database, such as `America/Chicago` or `UTC`. Declare the field as a `String`, and pass it to `in_tz` when you'd like to show a time in the user's time zone. For example, `laravel::now().in_tz(&form.timezone)?` returns the current time in that zone, as a `ZonedDateTime`. To learn more, check out the dates and time guide's section on [timezones](time.md#timezones).

<a name="date-times"></a>
#### Date-times

`datetime` requires an RFC 3339 timestamp with seconds and a UTC offset, such as `2024-02-29T09:30:00Z` or `2024-02-29T09:30:00-05:00`. A [`laravel::time::Timestamp`](time.md) field checks this format on its own, as the `datetime` rule does, and your handler receives the moment in time the value describes. When a rule such as `after` compares two timestamps, it compares the moments they describe, not the clock times as written. For example, `2024-02-29T09:30:00-05:00` is after `2024-02-29T10:00:00Z`, because 9:30 in New York is 14:30 in UTC:

```rust
use laravel::time::Timestamp;

#[laravel::input]
pub struct StoreAppointment {
    #[validate(required, label = "start time")]
    starts_at: Timestamp,
    #[validate(required, after(starts_at), label = "end time")]
    ends_at: Timestamp,
}
```

> [!NOTE]
> An HTML `<input type="datetime-local">` submits a time without an offset, so it can't pass `datetime`. Validate it with `date_format("%Y-%m-%dT%H:%M")`, and choose the time zone in your handler.

<a name="date-formats"></a>
#### Date formats

The `date` and `datetime` rules accept only the standard formats that a browser's date inputs and most APIs send, such as `2024-02-29`. Sometimes dates arrive in another format, such as a birthday that users type as `29/02/2024` into a plain text input. For those fields, use `date_format` instead, with the format you expect, written as a [strftime format](https://docs.rs/jiff/latest/jiff/fmt/strtime/index.html) such as `%d/%m/%Y`. The text must be a real date in exactly that format, so `%d/%m/%Y` rejects both `29/02/2023` and `1/02/2024`.

Since the text isn't in a standard format, declare the field as a `String`, and parse it into a date after validation:

```rust
use laravel::time::civil::Date;
use laravel::validation::Valid;

#[laravel::input]
#[validate(authenticated)]
pub struct UpdateProfile {
    #[validate(required, date_format("%d/%m/%Y"))]
    birthday: String,
}

pub async fn update(Valid(form): Valid<UpdateProfile>) -> laravel::Result<Redirect> {
    let birthday = Date::strptime("%d/%m/%Y", &form.birthday)?;

    // Store the birthday...

    Ok(Redirect::back())
}
```

The date comparison rules, such as `after` and `today_or_after`, only understand the standard formats. So to compare a date that arrives in another format, parse it in your handler and compare it there.

<a name="formats"></a>
### Formats

| Attribute | Passes when the value is |
| --- | --- |
| `email` | An email address |
| `url` | An `http` or `https` URL |
| `url("https", "wss")` | A URL with one of the schemes |
| `uuid` | A UUID in its hyphenated form |
| `uuid(7)` | A UUID of version 7 |
| `ulid` | A ULID |
| `ip` | An IPv4 or IPv6 address |
| `ipv4` | An IPv4 address |
| `ipv6` | An IPv6 address |
| `mac_address` | A MAC address |
| `hex_color` | A color such as `#1e90ff` |
| `json` | JSON text |
| `base64` | Padded Base64 text |
| `regex(r"\A[A-Z]{3}\z")` | Text that matches the pattern |
| `not_regex(r"(?i)admin")` | Text that doesn't match the pattern |

For example, this form checks a contact's email address, an optional website, and a callback URL that must use HTTPS:

```rust
#[laravel::input]
pub struct UpdateContact {
    #[validate(required, email)]
    email: String,
    #[validate(url)]
    website: Option<String>,
    #[validate(url("https").message("Please enter an HTTPS callback URL."))]
    callback: Option<String>,
}
```

Most of the time, you don't need the `ip`, `uuid`, or `ulid` rules. Declare the field with the type it holds instead, such as `std::net::IpAddr`, `Ipv4Addr`, or `Ipv6Addr` for an IP address, or `laravel::str::Uuid` or `laravel::str::Ulid` for an ID. Laravel checks the value's format as the matching rule would, and shows the rule's error message when the format is wrong. Your handler then receives the parsed value:

```rust
use std::net::IpAddr;

use laravel::str::Uuid;

#[laravel::input]
pub struct StoreDevice {
    device_id: Uuid,
    address: IpAddr,
}
```

Use the rules on `String` fields, or to require a UUID version, as in `uuid(7)`.

<a name="regular-expressions"></a>
#### Regular expressions

Patterns use [Rust regex syntax](https://docs.rs/regex/latest/regex/#syntax), without `/` delimiters. A pattern matches anywhere in the text, so anchor it with `\A` and `\z` to match the whole value:

```rust
#[laravel::input]
pub struct StoreProduct {
    #[validate(required, regex(r"\A[A-Z]{3}-[0-9]{4}\z"))]
    sku: String,
}
```

Rust's regex syntax doesn't support look-around or backreferences.

<a name="presence-and-acceptance"></a>
### Presence and acceptance

| Attribute | Passes when the field is |
| --- | --- |
| `required` | Present and not empty. `0` and `false` pass |
| `filled` | Not empty, if it's present |
| `present` | Present, even if empty |
| `missing` | Absent. Even a `null` fails |
| `prohibited` | Absent or empty |
| `accepted` | `"yes"`, `"on"`, `"1"`, `1`, `true`, or `"true"` |
| `declined` | `"no"`, `"off"`, `"0"`, `0`, `false`, or `"false"` |

An empty value is `null`, blank text, or an empty list. Unlike other rules, these rules check fields that are missing or empty. When one of them fails, Laravel skips the field's later rules. The one rule that doesn't do this is `prohibited`. If a field the user shouldn't have sent is also malformed, the user sees both errors. To learn more about rules that only apply when another field has a certain value, such as `required_if`, check out [conditional rules](#conditional-rules).

Use `accepted` for a checkbox that the user must tick, such as accepting your terms of service. A browser doesn't submit an unchecked checkbox at all, so give an optional checkbox's `bool` field `#[serde(default)]`. Without it, an unchecked box fails with "The newsletter field is required.":

```rust
use laravel::hash::Password;

#[laravel::input]
pub struct Register {
    #[validate(required, email)]
    email: String,
    #[validate(required, password, confirmed)]
    password: Password,
    #[validate(accepted)]
    terms: bool,
    #[serde(default)]
    newsletter: bool,
}
```

<a name="database-records"></a>
### Database records

`unique` checks that no row of a table already has the submitted value, such as an email address that's already taken. `exists` checks that some row of a table has the submitted value, such as the ID of a category the user picked. Pass each rule the column of the [model](models.md) to check:

```rust
use crate::models::{Category, Post, Tag};

#[laravel::input]
pub struct StorePost {
    #[validate(required, max_length(255), unique(Post::slug))]
    slug: String,
    #[validate(required, exists(Category::id))]
    category_id: i64,
    #[validate(bail, max_items(20), each(exists(Tag::id)))]
    tag_ids: Vec<i64>,
}
```

The rules query the model's table on the model's [database connection](database.md). The field's type must match the column's type, so a `String` field with `exists(Category::id)` doesn't compile.

For a table without a model, pass the table's name and then the column's name, as in `exists("categories", "id")`. Without a column name, the rule uses the field's Rust name, so `unique("posts")` on `slug` checks `posts.slug`. A table name always queries the default connection.

Each rule checks one value. To check each ID in a list, use `each(exists(..))`. That runs one query per item, so limit the list with `max_items` and add `bail`, which stops a list that's too long before any queries run.

The comparison follows the column's collation. A MySQL column with a case-insensitive collation finds `Taylor@example.com` when the row has `taylor@example.com`, while PostgreSQL and SQLite compare text exactly. For fields like email addresses, add `#[transform(lowercase)]` to normalize the value before validation and storage, as [Transforming input fields](#transforming-input-fields) describes.

<a name="ignoring-a-row"></a>
#### Ignoring a row

When users update their profile, their current email address is already in the `users` table, so a plain `unique` rule reports it as taken. Add `ignore = user` to skip the logged-in user's row:

```rust
#[laravel::input]
pub struct UpdateProfile {
    #[validate(required, email, unique(User::email, ignore = user))]
    email: String,
}
```

A page that edits another record has the same problem. On `PUT /teams/{team}`, the team's own row already holds its current name. Add `ignore = route("team")` to skip the team that the URL names:

```rust
use laravel::model::update;
use laravel::prelude::*;

use crate::models::Team;

#[laravel::input(fills = Team)]
#[validate(authenticated)]
pub struct UpdateTeam {
    #[validate(required, unique(Team::name, ignore = route("team")))]
    name: String,
}

// PUT /teams/{team}
pub async fn update(
    mut team: Team,
    Valid(input): Valid<UpdateTeam>,
) -> laravel::Result<Redirect> {
    update!(team { ..input }).await?;

    Ok(Redirect::back())
}
```

The rule finds the team as a `team: Team` handler argument would, so it also works for a team route that uses a slug.

`ignore = user` reads the user from the session, so it needs a route with a session or a [request guard](authentication.md). When the ID comes from somewhere else, add the rule with `Rule::unique(..).ignore(id)` in a [`rules` function](#adding-rules-from-the-request), or check the record in your handler and return an error with [`invalid!`](#adding-errors-after-validation).

<a name="filtering-rows"></a>
#### Filtering rows

Sometimes only some rows should count, such as categories that haven't been archived. `filter` limits a `unique` or `exists` rule to the rows that meet a [query builder condition](queries.md#conditions). For example, this rule only accepts categories that aren't archived:

```rust
use crate::models::Category;

#[laravel::input]
pub struct StorePost {
    #[validate(required, exists(Category::id, filter = Category::archived_at.is_null()))]
    category_id: i64,
}
```

Combine conditions with `&`, `|`, and `!`, as in `filter = Category::active.eq(true) & !Category::hidden.eq(true)`. With a table name, write the condition with `laravel::db::col`, as in `exists("categories", "id", filter = col("archived_at").is_null())`.

On a route that uses [route model binding](models.md#route-model-binding), such as `POST /projects/{project}/issues`, a filter often needs the bound model. Here, an issue's labels must belong to the project in the URL. To compare a column with that project's key, write `route::<Project>("project")` in the condition. The rule finds the project that `{project}` names and compares the column with its key:

```rust
use laravel::prelude::*;

use crate::models::{Label, Project};

#[laravel::input]
#[validate(authenticated)]
pub struct StoreIssue {
    #[validate(required, max_length(255))]
    title: String,
    #[serde(default)]
    #[validate(
        max_items(10),
        each(exists(Label::id, filter = Label::project_id.eq(route::<Project>("project")))),
    )]
    label_ids: Vec<i64>,
}

// POST /projects/{project}/issues
pub async fn store(
    project: Project,
    Valid(input): Valid<StoreIssue>,
) -> laravel::Result<Redirect> {
    // Create the issue...

    Ok(Redirect::back())
}
```

A label from another project fails with "The selected label_ids.0 is invalid."

When a condition needs a route parameter that isn't a model, add the rule in your [`rules` function](#adding-rules-from-the-request). For example, if an invitation's email address must be unique within the team named in the route, read the route parameter and filter `Rule::unique` with it:

```rust
use laravel::prelude::*;
use laravel::validation::{Rule, Rules, ValidatesRequest};

use crate::models::Member;

#[laravel::input]
pub struct StoreInvitation {
    #[validate(required, email)]
    email: String,
}

impl ValidatesRequest for StoreInvitation {
    async fn authorize(request: &Request) -> laravel::Result<bool> {
        Ok(request.authenticated().await?)
    }

    async fn rules(&self, request: &Request, rules: Rules) -> laravel::Result<Rules> {
        let team: i64 = request
            .route("team")
            .and_then(|id| id.parse().ok())
            .or_abort(404)?;

        Ok(rules.field(
            "email",
            [Rule::unique(Member::email).filter(Member::team_id.eq(team))],
        ))
    }
}
```

`Rule::unique` and `Rule::exists` return builders so you may chain options such as `ignore` and `filter`. Because a builder has a different type from other rules, combine it with other rules in a tuple rather than an array:

```rust
rules.field(
    "email",
    (
        Rule::max_length(255),
        Rule::unique(Member::email).filter(Member::team_id.eq(team)),
    ),
)
```

<a name="passwords"></a>
### Passwords

When users choose a new password, such as on your registration and password reset forms, you'll usually want every form to enforce the same complexity requirements. The `password` rule validates a field against your application's default password rules:

```rust
use laravel::hash::Password;

#[laravel::input]
pub struct ResetPassword {
    #[validate(required, email)]
    email: String,
    #[validate(required, password, confirmed)]
    password: Password,
}
```

By default, the `password` rule requires at least 8 characters. To customize your application's password requirements in one place, register a `PasswordRule` inside `with_services` in `src/app.rs`:

```rust
use laravel::validation::PasswordRule;

Application::configure()
    .with_services(|app| {
        app.instance(PasswordRule::min(8).letters().mixed_case().numbers());
    })
```

| Method | Requires |
| --- | --- |
| `PasswordRule::min(8)` | At least 8 characters |
| `max(64)` | At most 64 characters |
| `letters()` | At least one letter |
| `mixed_case()` | At least one uppercase and one lowercase letter |
| `numbers()` | At least one number |
| `symbols()` | At least one symbol, such as punctuation or a space |

If a specific form needs different requirements than your application defaults, such as an admin password requiring 12 characters and a symbol, pass those options directly to the `password` rule:

```rust
#[validate(required, password(min = 12, symbols), confirmed)]
password: Password,
```

<a name="current-password"></a>
### Current password

`current_password` checks that the field matches the logged-in user's password. Use it on forms that change a user's password or email address:

```rust
use laravel::hash::Password;

#[laravel::input]
pub struct UpdatePassword {
    #[validate(required, current_password)]
    current_password: Password,
    #[validate(required, password, confirmed)]
    password: Password,
}
```

The rule fails with "The password is incorrect." for a wrong password and for a guest. Like `ignore = user`, it reads the user from the session or a [request guard](authentication.md).

Declare password fields as `laravel::hash::Password` rather than `String`, as this form does. A `Password` keeps the plain-text password out of your logs, and Laravel never flashes it to the session as old input. To learn more, check out the hashing guide's section on [password fields](hashing.md#password-fields).

<a name="files"></a>
### Files

To validate an [uploaded file](requests.md#files), declare it as an `UploadedFile` field and put the file's rules on the field. Your handler then receives the file in the validated struct, so it may store the file:

```rust
use laravel::http::UploadedFile;
use laravel::prelude::*;

#[laravel::input]
#[validate(authenticated)]
pub struct UpdateProfile {
    #[validate(required, max_length(255))]
    name: String,
    #[validate(required, image, max_kilobytes(2048))]
    avatar: UploadedFile,
    #[validate(mimes("pdf"), max_kilobytes(10240))]
    resume: Option<UploadedFile>,
}

pub async fn update(Valid(form): Valid<UpdateProfile>) -> laravel::Result<Redirect> {
    let path = form.avatar.store("avatars").disk("public").await?;

    // Save the avatar's path...

    Ok(Redirect::back())
}
```

Use `Option<UploadedFile>` for an optional file. For an `<input type="file" multiple>` named `photos[]`, use `Vec<UploadedFile>`, and the rules check every file. `min_items` and `max_items` limit how many files the list holds.

| Attribute | Passes when the field is |
| --- | --- |
| `file` | An uploaded file |
| `image` | A JPEG, PNG, GIF, BMP, or WebP image |
| `mimes("pdf", "video/*")` | A file of one of these types, named by extension, such as `pdf`, or by MIME type, such as `video/*` for any video |
| `extensions("csv")` | A file whose name has one of these extensions |
| `min_kilobytes(10)` | A file of at least 10 kilobytes |
| `max_kilobytes(2048)` | A file of at most 2,048 kilobytes |

`image` and `mimes` check the file's contents, not the name the user gave it, so a renamed text file fails `image`. SVG fails `image`, because an SVG can carry scripts.

A text format such as CSV has nothing in its contents that identifies it, so `mimes("csv")` rejects every CSV file. Check those files with `extensions` instead. It only looks at the end of the file's name, such as `.csv`, so it can't tell whether a file named `contacts.csv` really is a CSV.

The [`LimitUploads`](middleware.md#body-size) middleware rejects a form that's too large before validation reads it, so set its limit above your largest `max_kilobytes`.

<a name="conditional-rules"></a>
## Conditional rules

Some fields matter only when another field has a certain value. A shipping address is required when the customer wants delivery, and pickup instructions make no sense then. Declare such fields as `Option`, so they may be absent when their condition doesn't apply:

```rust
#[laravel::input]
pub struct StoreShipment {
    #[validate(required, one_of("ship", "pickup"))]
    delivery: String,
    #[validate(required_if(delivery, "ship"))]
    address: Option<String>,
    #[validate(prohibited_if(delivery, "ship"))]
    pickup_notes: Option<String>,
}
```

| Attribute | The field is required, or must be empty |
| --- | --- |
| `required_if(delivery, "ship")` | Required when `delivery` is `ship` |
| `required_unless(delivery, "pickup")` | Required unless `delivery` is `pickup` |
| `required_with(phone, email)` | Required when any of the fields isn't empty |
| `required_with_all(phone, email)` | Required when none of the fields is empty |
| `required_without(phone, email)` | Required when any of the fields is empty |
| `required_without_all(phone, email)` | Required when all of the fields are empty |
| `required_if_accepted(terms)` | Required when the field is [accepted](#presence-and-acceptance) |
| `required_if_declined(terms)` | Required when the field is declined |
| `prohibited_if(delivery, "pickup")` | Empty when `delivery` is `pickup` |
| `prohibited_unless(delivery, "ship")` | Empty unless `delivery` is `ship` |
| `prohibited_if_accepted(terms)` | Empty when the field is accepted |
| `prohibited_if_declined(terms)` | Empty when the field is declined |
| `prohibits(phone, email)` | The other fields must be empty when this one isn't |
| `accepted_if(delivery, "ship")` | Accepted when `delivery` is `ship` |
| `declined_if(delivery, "ship")` | Declined when `delivery` is `ship` |

To check whether a field was submitted regardless of its value, use `present_if`, `present_unless`, `present_with`, `present_with_all`, `missing_if`, `missing_unless`, `missing_with`, or `missing_with_all`.

The field a conditional rule names belongs to the same struct as the rule. So when a form sends a list of addresses, each address checks its own country. In this example, an address in the US must have a state, while an address in Canada doesn't need one:

```rust
#[laravel::input]
pub struct StoreShipments {
    #[validate(required)]
    addresses: Vec<Address>,
}

#[laravel::input]
pub struct Address {
    #[validate(required)]
    country: String,
    #[validate(required_if(country, "US"))]
    state: Option<String>,
}
```

To check a field inside a nested struct, reference it through the struct's field path. For example, this order requires a phone number when its shipping address is in the US:

```rust
#[laravel::input]
pub struct StoreOrder {
    shipping: Address,
    #[validate(required_if(shipping.country, "US"))]
    phone: Option<String>,
}
```

A conditional rule references the other field by its Rust name, even when the request sends it under another name. For example, a JavaScript client might send `shippingCountry` and `phoneNumber`, which `#[serde(rename_all = "camelCase")]` maps to the struct's `shipping_country` and `phone_number` fields. The rule still writes `shipping_country`, and every segment of a field path is checked at compile time, so a misspelled field won't compile:

```rust
#[laravel::input]
#[serde(rename_all = "camelCase")]
pub struct StoreOrder {
    shipping_country: String,
    #[validate(required_if(shipping_country, "US"))]
    phone_number: Option<String>,
}
```

Rules you add in code, such as in a [`rules` function](#adding-rules-from-the-request), work on the request's input directly, so they name fields as the request sends them, such as `"phoneNumber"`.

The value a rule compares with must match exactly, so `required_if(country, "US")` doesn't apply when the request sends `"us"`.

Booleans and numbers are more forgiving. HTML forms send every value as text, so a checked checkbox arrives as `"on"` rather than `true`. Laravel accounts for this, so `required_if(enabled, true)` applies whether a JSON client sends `true` or a form sends `"on"`. In the same way, `required_if(count, 2)` matches both `2` and `"2"`.

<a name="nested-objects"></a>
## Nested objects

Sometimes a request nests related fields inside an object, such as the shipping and billing addresses of a checkout. A JSON client sends each address as an object, as in `{"shipping": {"city": "Chicago"}}`, and an HTML form names the address's fields with brackets, as in `<input name="shipping[city]">`. Laravel reads both into the same shape.

To validate a nested object, declare it as its own struct marked `#[laravel::input]`, such as an `Address` struct. A field of that type, such as `shipping: Address`, then checks the nested object with the `Address` struct's rules:

```rust
#[laravel::input]
pub struct StoreOrder {
    shipping: Address,
    billing: Option<Address>,
}

#[laravel::input]
pub struct Address {
    #[validate(required, max_length(255))]
    street: String,
    #[validate(required)]
    city: String,
    country: String,
    #[validate(required_if(country, "US"))]
    postal_code: Option<String>,
}
```

If the shipping address is missing its city, Laravel reports the error under `shipping.city`, so your form can show it next to the right input. The `billing` field is an `Option`, so a customer may leave out the billing address, such as to be billed at the shipping address. When the request does include a billing address, Laravel checks it with the same `Address` rules.

Only `StoreOrder` needs to say who may submit the form, such as with `#[validate(anyone)]`. The `Address` struct doesn't, because Laravel only checks it as part of an order.

When you accept a nested object as a map instead of a struct, you may restrict its keys with `allowed_keys` and `required_keys`. For example, you might allow a contact's `name` and `email` while rejecting any other keys, and require that the `email` key is always present (even if its value is `null`):

```rust
use std::collections::HashMap;

#[laravel::input]
#[validate(anyone)]
pub struct UpdateContact {
    #[validate(allowed_keys("name", "email"), required_keys("email"))]
    contact: HashMap<String, Option<String>>,
}
```

Map values support the same per-entry validation as lists. A `HashMap` or `BTreeMap` whose values are a `#[laravel::input]` struct validates every entry with that struct's rules, and `each(...)` applies rules to each value in a map of strings, numbers, or files. For example, a form that submits a translated title per language (`titles[en]`, `titles[fr]`) might cap every title's length:

```rust
use std::collections::HashMap;

#[laravel::input]
#[validate(anyone)]
pub struct StorePost {
    #[validate(required, each(required, max_length(255)))]
    titles: HashMap<String, String>,
}
```

Laravel reports a value's errors under its key, such as `titles.fr`.

<a name="validating-lists"></a>
## Validating lists

Many forms send lists, such as the items in an order or the tags on a post. A `Vec` field of a struct marked `#[laravel::input]` validates every item with that struct's rules. For a list of text or numbers, put the rules for each item in `each(...)`:

```rust
use crate::models::Product;

#[laravel::input]
pub struct StoreOrder {
    #[validate(required, max_items(50))]
    items: Vec<OrderItem>,
    #[validate(max_items(10), distinct, each(required, max_length(50)))]
    tags: Vec<String>,
}

#[laravel::input]
pub struct OrderItem {
    #[validate(required, exists(Product::id))]
    product_id: i64,
    #[validate(required, min_value(1))]
    quantity: u32,
}
```

Rules outside `each(...)` apply to the list itself, so `required` rejects an empty list. Laravel reports an item's errors in "dot" notation, with the item's position in the list, such as `items.2.quantity` for the quantity of the third item, or `tags.3` for the fourth tag. Forms submit lists with brackets, as in `tags[]=rust` or `items[0][quantity]=2`, and JSON clients send arrays.

| Attribute | Passes when the list |
| --- | --- |
| `min_items(1)` | Has at least 1 item |
| `max_items(10)` | Has at most 10 items |
| `distinct` | Has no duplicate items |
| `contains("editor")` | Includes every one of the listed values |
| `doesnt_contain("admin")` | Includes none of the listed values |
| `list` | Has keys `0`, `1`, `2`, and so on, in order |

`Option<Vec<T>>` accepts a missing list, and `Vec<Option<T>>` accepts `null` items.

<a name="contains-and-distinct"></a>
### Contains and distinct

`contains`, `doesnt_contain`, and `distinct` compare text case-sensitively and untyped JSON values strictly. On numeric or boolean collections such as `Vec<u64>` or `Vec<bool>`, they compare the decoded numeric or boolean values so `"1"` and `1` match:

```rust
#[laravel::input]
pub struct UpdateRoles {
    #[validate(required, contains("member"), doesnt_contain("owner"), distinct)]
    roles: Vec<String>,
}
```

<a name="custom-messages-and-labels"></a>
## Custom messages and labels

Every built-in rule has an English message with the field's name filled in, such as "The email field is required." To show a different name in the messages, such as "email address" instead of "email", set the field's `label`. To replace a rule's message, chain `.message(...)` directly onto the rule:

```rust
#[laravel::input]
pub struct StoreUser {
    #[validate(
        required.message("Please enter your :attribute."),
        email,
        label = "email address",
    )]
    email: String,
}
```

A missing email now reads "Please enter your email address.", and an invalid one reads "The email address field must be a valid email address." Labels change only the message, not the field's key in `errors`.

When a rule's message mentions another field, it uses that field's label too. For example, if `starts_on` has the label "arrival date", and `ends_on` has the label "departure date", the `after(starts_on)` rule on `ends_on` fails with "The departure date field must be a date after arrival date."

For a list, put rules that check the whole list, such as `distinct`, on the field. Put rules that check one item inside `each(...)`. You may give either kind of rule a custom message, and you may chain `.label(...)` onto `each(...)` to name the items:

```rust
#[laravel::input]
pub struct StoreArticle {
    #[validate(
        max_items(10).message("Choose at most :max tags."),
        distinct.message("Choose a different name for each tag."),
        each(
            required.message("Tag #:position can't be blank."),
            max_length(50).message(":Attribute #:position must be at most :max characters."),
        )
        .label("tag"),
    )]
    tags: Vec<String>,
}
```

Messages may use these placeholders:

| Placeholder | Value |
| --- | --- |
| `:attribute` | The field's label. Without one, its name in words, so `last_name` reads "last name" |
| `:Attribute`, `:ATTRIBUTE` | The label with its first letter capitalized, or in capitals |
| `:min`, `:max`, `:digits` | The rule's limits or digit count |
| `:other`, `:date` | The label of the field that a rule compares with |
| `:value`, `:values` | The value or values that a rule compares with |
| `:format` | The formats of `date_format` |
| `:index`, `:position` | The list item's index, from 0, or its position, from 1 |

A field's type checks its value too, even without a rule. For example, a `u32` field rejects `"two"`, and a `Uuid` field rejects text that isn't a UUID. To replace the message for that check, set `invalid` on the field (or chain `.invalid(...)` onto `each(...)` for list items):

```rust
use laravel::str::Uuid;

#[laravel::input]
pub struct StoreTickets {
    #[validate(invalid = "Enter a whole number of tickets.")]
    quantity: u32,
    #[validate(invalid = "That event ID isn't valid.")]
    event_id: Uuid,
}
```

The `invalid` message only replaces the message for a value that doesn't fit the field's type. Failures of the rules you declare, such as `required` or `max_length`, keep their own messages.

<a name="custom-rules"></a>
## Custom rules

When the built-in rules don't cover a check, write your own. Implement `ValidationRule` and use the rule in `#[validate(...)]`. You don't register it anywhere:

```rust
use laravel::validation::{Field, RuleError, ValidationRule};

pub struct Slug;

impl ValidationRule for Slug {
    async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
        match field.value.and_then(|value| value.as_str()) {
            Some(value) if value.chars().all(|c| c.is_ascii_lowercase() || c == '-') => Ok(()),
            _ => Err(field.reject("The :attribute field must be a slug.")),
        }
    }
}

#[laravel::input]
pub struct StoreArticle {
    #[validate(required, max_length(100), Slug)]
    slug: String,
}
```

A custom rule is any Rust expression, such as `Slug`, `my_package::Slug`, or `Slug::new().max_length(50)`. To add one in code, such as in a [`rules` function](#adding-rules-from-the-request), wrap it with `Rule::custom(Slug)`.

`Field` gives the rule what it needs to check:

- `value` is the submitted `InputValue`, or `None` when the field is missing. It holds text, numbers, booleans, arrays, objects, and uploaded files alike, so a custom rule may inspect a file with `value.as_file()` or read text with `value.as_str()`.
- `name` is the field's path, such as `items.7.slug`.
- `get("other")` reads another field of the same struct, or `None` when the request didn't send it. In a list or map of addresses, `get("country")` reads the same address's country. Use "dot" notation to reach into a nested object, as in `get("shipping.country")`.
- `input` is the whole request's input, for reading a field outside the current object, such as a top-level field from inside a list entry.

Both `get` and `input` name fields as the request sends them, such as `"shippingCountry"` for a struct with `#[serde(rename_all = "camelCase")]`, and return `InputValue` values. For example, this rule reads the country of the address it checks:

```rust
impl ValidationRule for PostalCode {
    async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
        let country = field.get("country").and_then(|value| value.as_str());

        // Check the postal code's format for the country...

        Ok(())
    }
}
```

Return `Ok(())` to accept the value, or `Err(field.reject(message))` to reject it. Laravel fills in these placeholders in your rule's message:

| Placeholder | Value |
| --- | --- |
| `:attribute` | The field's label, or its name in words, so `postal_code` reads "postal code" |
| `:Attribute`, `:ATTRIBUTE` | The same name with its first letter capitalized, or in capitals |
| `:index`, `:position` | For an item in a list, its index from 0, or its position from 1 |

To add placeholders of your own, build a `Message` and give each placeholder a value with `with`. For example, the `PostalCode` rule might name the country whose format the postal code doesn't match:

```rust
use laravel::validation::Message;

return Err(field.reject(
    Message::new("The :attribute doesn't match the format for :country.")
        .with("country", country),
));
```

To replace a custom rule's message for one field, chain `.message(...)` onto the rule, just as you would for a built-in rule. The replacement may use your rule's placeholders too:

```rust
#[validate(required, Slug.message("Choose a valid :attribute."))]
slug: String,
```

Like most built-in rules, a custom rule skips missing fields, blank strings, and `null` on nullable fields. To check those values too, return `true` from the rule's `implicit` method.

<a name="async-rules"></a>
### Asynchronous checks

Rules are async, so a rule may query the database or send an HTTP request, and return their errors with `?`. Say your application keeps a `BlockedDomain` model of email domains it doesn't accept for sign-ups. A `unique(BlockedDomain::domain)` rule would compare the whole address with the column, so this rule looks up only the part after the `@`:

```rust
use laravel::validation::{Field, RuleError, ValidationRule};

use crate::models::BlockedDomain;

pub struct AllowedEmailDomain;

impl ValidationRule for AllowedEmailDomain {
    async fn validate(&self, field: &Field<'_>) -> Result<(), RuleError> {
        let Some((_, domain)) = field
            .value
            .and_then(|value| value.as_str()?.rsplit_once('@'))
        else {
            return Ok(());
        };

        let blocked = BlockedDomain::query()
            .filter(BlockedDomain::domain.eq(domain.to_lowercase()))
            .exists()
            .await?;

        if blocked {
            return Err(field.reject("The :attribute uses a domain we don't accept."));
        }

        Ok(())
    }
}

#[laravel::input]
pub struct Register {
    #[validate(bail, required, email, AllowedEmailDomain)]
    email: String,
}
```

Put cheap rules first and add `bail`, so input that's already invalid never reaches the query. An error returned with `?`, such as a database outage, stops validation and reaches your error handler, rather than showing up as a field error.

<a name="testing"></a>
## Testing

The application's [test client](testing.md) has assertions for validation errors. They read the errors from a JSON response or from the session after a redirect:

```rust
use laravel::testing::prelude::*;

#[laravel::test]
async fn a_post_needs_a_title(app: Application) {
    app.post("/posts")
        .json(json!({ "title": "", "body": "Hello, world." }))
        .await
        .assert_status(422)
        .assert_invalid(&["title"])
        .assert_invalid_messages(&[("title", "required")])
        .assert_valid(&["body"]);
}
```

`assert_invalid_messages` checks that each field has an error containing the text. `assert_valid(&[])` checks that there were no errors at all. For a page with [several forms](#pages-with-several-forms), check a named form's errors with `assert_invalid_in("login", &["email"])`.

A browser form that fails validation goes back to the page it came from. So to test a form, send the request `from` that page, then check the redirect, the errors, and the input Laravel flashed to the session:

```rust
app.post("/posts")
    .from("/posts/create")
    .form([("title", ""), ("body", "Hello, world.")])
    .await
    .assert_redirect_back_with_errors(&["title"])
    .assert_session_has_input("body", "Hello, world.");
```

To learn more, check out the testing guide's section on [redirecting back](testing.md#redirecting-back).