ferro-rs 0.2.12

A Laravel-inspired web framework for Rust
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
//! Built-in validation rules.

use crate::validation::translate_validation;
use crate::validation::Rule;
use regex::Regex;
use serde_json::Value;
use std::sync::LazyLock;

// ============================================================================
// Required Rules
// ============================================================================

/// Field must be present and not empty.
pub struct Required;

/// Creates a required validation rule.
pub const fn required() -> Required {
    Required
}

impl Rule for Required {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        let is_empty = match value {
            Value::Null => true,
            Value::String(s) => s.trim().is_empty(),
            Value::Array(a) => a.is_empty(),
            Value::Object(o) => o.is_empty(),
            _ => false,
        };

        if is_empty {
            Err(
                translate_validation("validation.required", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} field is required.")),
            )
        } else {
            Ok(())
        }
    }

    fn name(&self) -> &'static str {
        "required"
    }
}

/// Field is required if another field equals a value.
pub struct RequiredIf {
    other: String,
    value: Value,
}

/// Creates a required_if validation rule.
pub fn required_if(other: impl Into<String>, value: impl Into<Value>) -> RequiredIf {
    RequiredIf {
        other: other.into(),
        value: value.into(),
    }
}

impl Rule for RequiredIf {
    fn validate(&self, field: &str, value: &Value, data: &Value) -> Result<(), String> {
        let other_value = data.get(&self.other);
        if other_value == Some(&self.value) {
            Required.validate(field, value, data)
        } else {
            Ok(())
        }
    }

    fn name(&self) -> &'static str {
        "required_if"
    }
}

// ============================================================================
// Type Rules
// ============================================================================

/// Field must be a string.
pub struct IsString;

/// Creates a string validation rule.
pub const fn string() -> IsString {
    IsString
}

impl Rule for IsString {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() || value.is_string() {
            Ok(())
        } else {
            Err(
                translate_validation("validation.string", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} field must be a string.")),
            )
        }
    }

    fn name(&self) -> &'static str {
        "string"
    }
}

/// Field must be an integer.
pub struct IsInteger;

/// Creates an integer validation rule.
pub const fn integer() -> IsInteger {
    IsInteger
}

impl Rule for IsInteger {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() || value.is_i64() || value.is_u64() {
            Ok(())
        } else if let Some(s) = value.as_str() {
            if s.parse::<i64>().is_ok() {
                Ok(())
            } else {
                Err(
                    translate_validation("validation.integer", &[("attribute", field)])
                        .unwrap_or_else(|| format!("The {field} field must be an integer.")),
                )
            }
        } else {
            Err(
                translate_validation("validation.integer", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} field must be an integer.")),
            )
        }
    }

    fn name(&self) -> &'static str {
        "integer"
    }
}

/// Field must be numeric.
pub struct Numeric;

/// Creates a numeric validation rule.
pub const fn numeric() -> Numeric {
    Numeric
}

impl Rule for Numeric {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() || value.is_number() {
            Ok(())
        } else if let Some(s) = value.as_str() {
            if s.parse::<f64>().is_ok() {
                Ok(())
            } else {
                Err(
                    translate_validation("validation.numeric", &[("attribute", field)])
                        .unwrap_or_else(|| format!("The {field} field must be a number.")),
                )
            }
        } else {
            Err(
                translate_validation("validation.numeric", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} field must be a number.")),
            )
        }
    }

    fn name(&self) -> &'static str {
        "numeric"
    }
}

/// Field must be a boolean.
pub struct IsBoolean;

/// Creates a boolean validation rule.
pub const fn boolean() -> IsBoolean {
    IsBoolean
}

impl Rule for IsBoolean {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() || value.is_boolean() {
            Ok(())
        } else if let Some(s) = value.as_str() {
            match s.to_lowercase().as_str() {
                "true" | "false" | "1" | "0" | "yes" | "no" => Ok(()),
                _ => Err(
                    translate_validation("validation.boolean", &[("attribute", field)])
                        .unwrap_or_else(|| format!("The {field} field must be true or false.")),
                ),
            }
        } else if let Some(n) = value.as_i64() {
            if n == 0 || n == 1 {
                Ok(())
            } else {
                Err(
                    translate_validation("validation.boolean", &[("attribute", field)])
                        .unwrap_or_else(|| format!("The {field} field must be true or false.")),
                )
            }
        } else {
            Err(
                translate_validation("validation.boolean", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} field must be true or false.")),
            )
        }
    }

    fn name(&self) -> &'static str {
        "boolean"
    }
}

/// Field must be an array.
pub struct IsArray;

/// Creates an array validation rule.
pub const fn array() -> IsArray {
    IsArray
}

impl Rule for IsArray {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() || value.is_array() {
            Ok(())
        } else {
            Err(
                translate_validation("validation.array", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} field must be an array.")),
            )
        }
    }

    fn name(&self) -> &'static str {
        "array"
    }
}

// ============================================================================
// Size Rules
// ============================================================================

/// Field must have a minimum size/length/value.
pub struct Min {
    min: f64,
}

/// Creates a min validation rule.
pub fn min(min: impl Into<f64>) -> Min {
    Min { min: min.into() }
}

impl Rule for Min {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        let size = get_size(value);
        if size < self.min {
            let unit = get_size_unit(value);
            let type_key = get_size_type_key("min", value);
            let min_str = format!("{}", self.min as i64);
            Err(
                translate_validation(&type_key, &[("attribute", field), ("min", &min_str)])
                    .unwrap_or_else(|| {
                        format!(
                            "The {} field must be at least {} {}.",
                            field, self.min as i64, unit
                        )
                    }),
            )
        } else {
            Ok(())
        }
    }

    fn name(&self) -> &'static str {
        "min"
    }
}

/// Field must have a maximum size/length/value.
pub struct Max {
    max: f64,
}

/// Creates a max validation rule.
pub fn max(max: impl Into<f64>) -> Max {
    Max { max: max.into() }
}

impl Rule for Max {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        let size = get_size(value);
        if size > self.max {
            let unit = get_size_unit(value);
            let type_key = get_size_type_key("max", value);
            let max_str = format!("{}", self.max as i64);
            Err(
                translate_validation(&type_key, &[("attribute", field), ("max", &max_str)])
                    .unwrap_or_else(|| {
                        format!(
                            "The {} field must not be greater than {} {}.",
                            field, self.max as i64, unit
                        )
                    }),
            )
        } else {
            Ok(())
        }
    }

    fn name(&self) -> &'static str {
        "max"
    }
}

/// Field must be between min and max size.
pub struct Between {
    min: f64,
    max: f64,
}

/// Creates a between validation rule.
pub fn between(min: impl Into<f64>, max: impl Into<f64>) -> Between {
    Between {
        min: min.into(),
        max: max.into(),
    }
}

impl Rule for Between {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        let size = get_size(value);
        if size < self.min || size > self.max {
            let unit = get_size_unit(value);
            let type_key = get_size_type_key("between", value);
            let min_str = format!("{}", self.min as i64);
            let max_str = format!("{}", self.max as i64);
            Err(translate_validation(
                &type_key,
                &[("attribute", field), ("min", &min_str), ("max", &max_str)],
            )
            .unwrap_or_else(|| {
                format!(
                    "The {} field must be between {} and {} {}.",
                    field, self.min as i64, self.max as i64, unit
                )
            }))
        } else {
            Ok(())
        }
    }

    fn name(&self) -> &'static str {
        "between"
    }
}

// ============================================================================
// Format Rules
// ============================================================================

static EMAIL_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap());

/// Field must be a valid email address.
pub struct Email;

/// Creates an email validation rule.
pub const fn email() -> Email {
    Email
}

impl Rule for Email {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        match value.as_str() {
            Some(s) if EMAIL_REGEX.is_match(s) => Ok(()),
            _ => Err(
                translate_validation("validation.email", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} field must be a valid email address.")),
            ),
        }
    }

    fn name(&self) -> &'static str {
        "email"
    }
}

static URL_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^https?://[^\s/$.?#].[^\s]*$").unwrap());

/// Field must be a valid URL.
pub struct Url;

/// Creates a URL validation rule.
pub const fn url() -> Url {
    Url
}

impl Rule for Url {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        match value.as_str() {
            Some(s) if URL_REGEX.is_match(s) => Ok(()),
            _ => Err(
                translate_validation("validation.url", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} field must be a valid URL.")),
            ),
        }
    }

    fn name(&self) -> &'static str {
        "url"
    }
}

/// Field must match a regex pattern.
pub struct Regex_ {
    pattern: Regex,
}

/// Creates a regex validation rule.
pub fn regex(pattern: &str) -> Regex_ {
    Regex_ {
        pattern: Regex::new(pattern).expect("Invalid regex pattern"),
    }
}

impl Rule for Regex_ {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        match value.as_str() {
            Some(s) if self.pattern.is_match(s) => Ok(()),
            _ => Err(
                translate_validation("validation.regex", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} field format is invalid.")),
            ),
        }
    }

    fn name(&self) -> &'static str {
        "regex"
    }
}

static ALPHA_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[a-zA-Z]+$").unwrap());

/// Field must contain only alphabetic characters.
pub struct Alpha;

/// Creates an alpha validation rule.
pub const fn alpha() -> Alpha {
    Alpha
}

impl Rule for Alpha {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        match value.as_str() {
            Some(s) if ALPHA_REGEX.is_match(s) => Ok(()),
            _ => Err(
                translate_validation("validation.alpha", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} field must only contain letters.")),
            ),
        }
    }

    fn name(&self) -> &'static str {
        "alpha"
    }
}

static ALPHA_NUM_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9]+$").unwrap());

/// Field must contain only alphanumeric characters.
pub struct AlphaNum;

/// Creates an alpha_num validation rule.
pub const fn alpha_num() -> AlphaNum {
    AlphaNum
}

impl Rule for AlphaNum {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        match value.as_str() {
            Some(s) if ALPHA_NUM_REGEX.is_match(s) => Ok(()),
            _ => Err(
                translate_validation("validation.alpha_num", &[("attribute", field)])
                    .unwrap_or_else(|| {
                        format!("The {field} field must only contain letters and numbers.")
                    }),
            ),
        }
    }

    fn name(&self) -> &'static str {
        "alpha_num"
    }
}

static ALPHA_DASH_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9_-]+$").unwrap());

/// Field must contain only alphanumeric characters, dashes, and underscores.
pub struct AlphaDash;

/// Creates an alpha_dash validation rule.
pub const fn alpha_dash() -> AlphaDash {
    AlphaDash
}

impl Rule for AlphaDash {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        match value.as_str() {
            Some(s) if ALPHA_DASH_REGEX.is_match(s) => Ok(()),
            _ => Err(
                translate_validation("validation.alpha_dash", &[("attribute", field)])
                    .unwrap_or_else(|| {
                        format!(
                    "The {field} field must only contain letters, numbers, dashes, and underscores."
                )
                    }),
            ),
        }
    }

    fn name(&self) -> &'static str {
        "alpha_dash"
    }
}

// ============================================================================
// Comparison Rules
// ============================================================================

/// Field must match another field.
pub struct Confirmed {
    confirmation_field: String,
}

/// Creates a confirmed validation rule.
pub fn confirmed() -> Confirmed {
    Confirmed {
        confirmation_field: String::new(), // Will be set based on field name
    }
}

impl Rule for Confirmed {
    fn validate(&self, field: &str, value: &Value, data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        let confirmation_field = if self.confirmation_field.is_empty() {
            format!("{field}_confirmation")
        } else {
            self.confirmation_field.clone()
        };

        let confirmation_value = data.get(&confirmation_field);
        if confirmation_value == Some(value) {
            Ok(())
        } else {
            Err(
                translate_validation("validation.confirmed", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} confirmation does not match.")),
            )
        }
    }

    fn name(&self) -> &'static str {
        "confirmed"
    }
}

/// Field must be in a list of values.
pub struct In {
    values: Vec<Value>,
}

/// Creates an in_array validation rule.
pub fn in_array<I, V>(values: I) -> In
where
    I: IntoIterator<Item = V>,
    V: Into<Value>,
{
    In {
        values: values.into_iter().map(|v| v.into()).collect(),
    }
}

impl Rule for In {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        if self.values.contains(value) {
            Ok(())
        } else {
            Err(
                translate_validation("validation.in", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The selected {field} is invalid.")),
            )
        }
    }

    fn name(&self) -> &'static str {
        "in"
    }
}

/// Field must not be in a list of values.
pub struct NotIn {
    values: Vec<Value>,
}

/// Creates a not_in validation rule.
pub fn not_in<I, V>(values: I) -> NotIn
where
    I: IntoIterator<Item = V>,
    V: Into<Value>,
{
    NotIn {
        values: values.into_iter().map(|v| v.into()).collect(),
    }
}

impl Rule for NotIn {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        if self.values.contains(value) {
            Err(
                translate_validation("validation.not_in", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The selected {field} is invalid.")),
            )
        } else {
            Ok(())
        }
    }

    fn name(&self) -> &'static str {
        "not_in"
    }
}

/// Field must be different from another field.
pub struct Different {
    other: String,
}

/// Creates a different validation rule.
pub fn different(other: impl Into<String>) -> Different {
    Different {
        other: other.into(),
    }
}

impl Rule for Different {
    fn validate(&self, field: &str, value: &Value, data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        let other_value = data.get(&self.other);
        if other_value == Some(value) {
            Err(translate_validation(
                "validation.different",
                &[("attribute", field), ("other", &self.other)],
            )
            .unwrap_or_else(|| {
                format!("The {} and {} fields must be different.", field, self.other)
            }))
        } else {
            Ok(())
        }
    }

    fn name(&self) -> &'static str {
        "different"
    }
}

/// Field must be the same as another field.
pub struct Same {
    other: String,
}

/// Creates a same validation rule.
pub fn same(other: impl Into<String>) -> Same {
    Same {
        other: other.into(),
    }
}

impl Rule for Same {
    fn validate(&self, field: &str, value: &Value, data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        let other_value = data.get(&self.other);
        if other_value != Some(value) {
            Err(translate_validation(
                "validation.same",
                &[("attribute", field), ("other", &self.other)],
            )
            .unwrap_or_else(|| format!("The {} and {} fields must match.", field, self.other)))
        } else {
            Ok(())
        }
    }

    fn name(&self) -> &'static str {
        "same"
    }
}

// ============================================================================
// Date Rules
// ============================================================================

/// Field must be a valid date.
pub struct Date;

/// Creates a date validation rule.
pub const fn date() -> Date {
    Date
}

impl Rule for Date {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        if value.is_null() {
            return Ok(());
        }

        if let Some(s) = value.as_str() {
            // Try common date formats
            if chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").is_ok()
                || chrono::NaiveDate::parse_from_str(s, "%d/%m/%Y").is_ok()
                || chrono::NaiveDate::parse_from_str(s, "%m/%d/%Y").is_ok()
                || chrono::DateTime::parse_from_rfc3339(s).is_ok()
            {
                return Ok(());
            }
        }

        Err(
            translate_validation("validation.date", &[("attribute", field)])
                .unwrap_or_else(|| format!("The {field} field must be a valid date.")),
        )
    }

    fn name(&self) -> &'static str {
        "date"
    }
}

// ============================================================================
// Special Rules
// ============================================================================

/// Field is optional - only validate if present.
pub struct Nullable;

/// Creates a nullable validation rule.
pub const fn nullable() -> Nullable {
    Nullable
}

impl Rule for Nullable {
    fn validate(&self, _field: &str, _value: &Value, _data: &Value) -> Result<(), String> {
        // This is a marker rule - validator handles it specially
        Ok(())
    }

    fn name(&self) -> &'static str {
        "nullable"
    }
}

/// Field must be accepted (yes, on, 1, true).
pub struct Accepted;

/// Creates an accepted validation rule.
pub const fn accepted() -> Accepted {
    Accepted
}

impl Rule for Accepted {
    fn validate(&self, field: &str, value: &Value, _data: &Value) -> Result<(), String> {
        let accepted = match value {
            Value::Bool(true) => true,
            Value::Number(n) => n.as_i64() == Some(1),
            Value::String(s) => {
                matches!(s.to_lowercase().as_str(), "yes" | "on" | "1" | "true")
            }
            _ => false,
        };

        if accepted {
            Ok(())
        } else {
            Err(
                translate_validation("validation.accepted", &[("attribute", field)])
                    .unwrap_or_else(|| format!("The {field} field must be accepted.")),
            )
        }
    }

    fn name(&self) -> &'static str {
        "accepted"
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Get the size of a value (length for strings/arrays, value for numbers).
fn get_size(value: &Value) -> f64 {
    match value {
        Value::String(s) => s.chars().count() as f64,
        Value::Array(a) => a.len() as f64,
        Value::Object(o) => o.len() as f64,
        Value::Number(n) => n.as_f64().unwrap_or(0.0),
        _ => 0.0,
    }
}

/// Get the appropriate unit for size validation messages.
fn get_size_unit(value: &Value) -> &'static str {
    match value {
        Value::String(_) => "characters",
        Value::Array(_) => "items",
        Value::Object(_) => "items",
        _ => "",
    }
}

/// Get the type-specific translation key for size rules (min, max, between).
fn get_size_type_key(rule: &str, value: &Value) -> String {
    let suffix = match value {
        Value::String(_) => "string",
        Value::Array(_) | Value::Object(_) => "array",
        _ => "numeric",
    };
    format!("validation.{rule}.{suffix}")
}

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

    #[test]
    fn test_required() {
        let rule = required();
        let data = json!({});

        assert!(rule.validate("name", &json!("John"), &data).is_ok());
        assert!(rule.validate("name", &json!(null), &data).is_err());
        assert!(rule.validate("name", &json!(""), &data).is_err());
        assert!(rule.validate("name", &json!("  "), &data).is_err());
    }

    #[test]
    fn test_email() {
        let rule = email();
        let data = json!({});

        assert!(rule
            .validate("email", &json!("test@example.com"), &data)
            .is_ok());
        assert!(rule.validate("email", &json!("invalid"), &data).is_err());
        assert!(rule.validate("email", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_min_max() {
        let data = json!({});

        // String length
        assert!(min(3).validate("name", &json!("John"), &data).is_ok());
        assert!(min(5).validate("name", &json!("John"), &data).is_err());

        assert!(max(5).validate("name", &json!("John"), &data).is_ok());
        assert!(max(2).validate("name", &json!("John"), &data).is_err());

        // Numeric value
        assert!(min(18).validate("age", &json!(25), &data).is_ok());
        assert!(min(18).validate("age", &json!(15), &data).is_err());
    }

    #[test]
    fn test_between() {
        let rule = between(1, 10);
        let data = json!({});

        assert!(rule.validate("count", &json!(5), &data).is_ok());
        assert!(rule.validate("count", &json!(0), &data).is_err());
        assert!(rule.validate("count", &json!(11), &data).is_err());
    }

    #[test]
    fn test_in_array() {
        let rule = in_array(["active", "inactive", "pending"]);
        let data = json!({});

        assert!(rule.validate("status", &json!("active"), &data).is_ok());
        assert!(rule.validate("status", &json!("unknown"), &data).is_err());
    }

    #[test]
    fn test_confirmed() {
        let rule = confirmed();
        let data = json!({
            "password": "secret123",
            "password_confirmation": "secret123"
        });

        assert!(rule
            .validate("password", &json!("secret123"), &data)
            .is_ok());

        let bad_data = json!({
            "password": "secret123",
            "password_confirmation": "different"
        });
        assert!(rule
            .validate("password", &json!("secret123"), &bad_data)
            .is_err());
    }

    #[test]
    fn test_url() {
        let rule = url();
        let data = json!({});

        assert!(rule
            .validate("website", &json!("https://example.com"), &data)
            .is_ok());
        assert!(rule
            .validate("website", &json!("http://example.com/path"), &data)
            .is_ok());
        assert!(rule
            .validate("website", &json!("not-a-url"), &data)
            .is_err());
    }

    #[test]
    fn test_rules_call_translate_validation() {
        fn mock(key: &str, params: &[(&str, &str)]) -> Option<String> {
            let attr = params
                .iter()
                .find(|(k, _)| *k == "attribute")
                .map(|(_, v)| *v)
                .unwrap_or("?");
            Some(format!("[translated] {key}: attr={attr}"))
        }

        // OnceLock: if already set by another test, skip gracefully
        let was_set = crate::validation::bridge::VALIDATION_TRANSLATOR
            .set(mock as crate::validation::TranslatorFn)
            .is_ok();

        let result = required().validate("email", &json!(null), &json!({}));
        assert!(result.is_err());

        if was_set {
            let msg = result.unwrap_err();
            assert!(
                msg.contains("[translated]"),
                "Expected translated message, got: {msg}"
            );
            assert!(
                msg.contains("validation.required"),
                "Expected key in message, got: {msg}"
            );
        }
    }

    #[test]
    fn test_string() {
        let rule = string();
        let data = json!({});

        assert!(rule.validate("name", &json!("hello"), &data).is_ok());
        assert!(rule.validate("name", &json!(""), &data).is_ok());
        assert!(rule.validate("name", &json!(42), &data).is_err());
        assert!(rule.validate("name", &json!(true), &data).is_err());
        assert!(rule.validate("name", &json!([1, 2]), &data).is_err());
        // Null passthrough
        assert!(rule.validate("name", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_integer() {
        let rule = integer();
        let data = json!({});

        assert!(rule.validate("age", &json!(42), &data).is_ok());
        assert!(rule.validate("age", &json!(0), &data).is_ok());
        assert!(rule.validate("age", &json!(-5), &data).is_ok());
        // String integers are accepted
        assert!(rule.validate("age", &json!("123"), &data).is_ok());
        // Floats are not integers
        assert!(rule.validate("age", &json!(3.17), &data).is_err());
        assert!(rule.validate("age", &json!("hello"), &data).is_err());
        assert!(rule.validate("age", &json!(true), &data).is_err());
        // Null passthrough
        assert!(rule.validate("age", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_numeric() {
        let rule = numeric();
        let data = json!({});

        assert!(rule.validate("price", &json!(42), &data).is_ok());
        assert!(rule.validate("price", &json!(3.17), &data).is_ok());
        assert!(rule.validate("price", &json!(-10), &data).is_ok());
        // String numbers are accepted
        assert!(rule.validate("price", &json!("42.5"), &data).is_ok());
        assert!(rule.validate("price", &json!("hello"), &data).is_err());
        assert!(rule.validate("price", &json!(true), &data).is_err());
        // Null passthrough
        assert!(rule.validate("price", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_boolean() {
        let rule = boolean();
        let data = json!({});

        assert!(rule.validate("active", &json!(true), &data).is_ok());
        assert!(rule.validate("active", &json!(false), &data).is_ok());
        // String booleans are accepted
        assert!(rule.validate("active", &json!("true"), &data).is_ok());
        assert!(rule.validate("active", &json!("false"), &data).is_ok());
        assert!(rule.validate("active", &json!("yes"), &data).is_ok());
        assert!(rule.validate("active", &json!("no"), &data).is_ok());
        assert!(rule.validate("active", &json!("1"), &data).is_ok());
        assert!(rule.validate("active", &json!("0"), &data).is_ok());
        // Integer 0 and 1 are accepted
        assert!(rule.validate("active", &json!(1), &data).is_ok());
        assert!(rule.validate("active", &json!(0), &data).is_ok());
        // Non-boolean strings rejected
        assert!(rule.validate("active", &json!("maybe"), &data).is_err());
        // Other integers rejected
        assert!(rule.validate("active", &json!(42), &data).is_err());
        // Null passthrough
        assert!(rule.validate("active", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_array() {
        let rule = array();
        let data = json!({});

        assert!(rule.validate("items", &json!([1, 2, 3]), &data).is_ok());
        assert!(rule.validate("items", &json!([]), &data).is_ok());
        assert!(rule.validate("items", &json!(["a", "b"]), &data).is_ok());
        assert!(rule.validate("items", &json!("not array"), &data).is_err());
        assert!(rule.validate("items", &json!(42), &data).is_err());
        assert!(rule.validate("items", &json!(true), &data).is_err());
        // Null passthrough
        assert!(rule.validate("items", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_required_if() {
        let data = json!({"role": "admin"});

        // role == admin, so name is required
        assert!(required_if("role", "admin")
            .validate("name", &json!(null), &data)
            .is_err());
        assert!(required_if("role", "admin")
            .validate("name", &json!(""), &data)
            .is_err());
        assert!(required_if("role", "admin")
            .validate("name", &json!("Alice"), &data)
            .is_ok());

        // role != "user", so name is not required
        assert!(required_if("role", "user")
            .validate("name", &json!(null), &data)
            .is_ok());
        assert!(required_if("role", "user")
            .validate("name", &json!(""), &data)
            .is_ok());
    }

    #[test]
    fn test_different() {
        let data = json!({"other_field": "b"});

        // Different values pass
        assert!(different("other_field")
            .validate("field", &json!("a"), &data)
            .is_ok());
        // Same values fail
        assert!(different("other_field")
            .validate("field", &json!("b"), &data)
            .is_err());
        // Null passthrough
        assert!(different("other_field")
            .validate("field", &json!(null), &data)
            .is_ok());
    }

    #[test]
    fn test_same() {
        let data = json!({"other_field": "a"});

        // Same values pass
        assert!(same("other_field")
            .validate("field", &json!("a"), &data)
            .is_ok());
        // Different values fail
        assert!(same("other_field")
            .validate("field", &json!("b"), &data)
            .is_err());
        // Null passthrough
        assert!(same("other_field")
            .validate("field", &json!(null), &data)
            .is_ok());
    }

    #[test]
    fn test_regex() {
        let rule = regex(r"^\d{3}-\d{4}$");
        let data = json!({});

        assert!(rule.validate("phone", &json!("123-4567"), &data).is_ok());
        assert!(rule.validate("phone", &json!("abc"), &data).is_err());
        assert!(rule.validate("phone", &json!("12-345"), &data).is_err());
        // Null passthrough
        assert!(rule.validate("phone", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_alpha() {
        let rule = alpha();
        let data = json!({});

        assert!(rule.validate("name", &json!("Hello"), &data).is_ok());
        assert!(rule.validate("name", &json!("abc"), &data).is_ok());
        assert!(rule.validate("name", &json!("Hello123"), &data).is_err());
        assert!(rule.validate("name", &json!("hello world"), &data).is_err());
        // Empty string does not match alpha regex
        assert!(rule.validate("name", &json!(""), &data).is_err());
        // Null passthrough
        assert!(rule.validate("name", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_alpha_num() {
        let rule = alpha_num();
        let data = json!({});

        assert!(rule.validate("code", &json!("Hello123"), &data).is_ok());
        assert!(rule.validate("code", &json!("abc"), &data).is_ok());
        assert!(rule.validate("code", &json!("123"), &data).is_ok());
        assert!(rule.validate("code", &json!("Hello!@#"), &data).is_err());
        assert!(rule.validate("code", &json!("hello world"), &data).is_err());
        // Null passthrough
        assert!(rule.validate("code", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_alpha_dash() {
        let rule = alpha_dash();
        let data = json!({});

        assert!(rule
            .validate("slug", &json!("hello-world_123"), &data)
            .is_ok());
        assert!(rule.validate("slug", &json!("abc"), &data).is_ok());
        assert!(rule.validate("slug", &json!("a-b_c"), &data).is_ok());
        assert!(rule.validate("slug", &json!("hello world"), &data).is_err());
        assert!(rule.validate("slug", &json!("hello!@#"), &data).is_err());
        // Null passthrough
        assert!(rule.validate("slug", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_not_in() {
        let rule = not_in(["banned", "blocked"]);
        let data = json!({});

        assert!(rule.validate("status", &json!("active"), &data).is_ok());
        assert!(rule.validate("status", &json!("approved"), &data).is_ok());
        assert!(rule.validate("status", &json!("banned"), &data).is_err());
        assert!(rule.validate("status", &json!("blocked"), &data).is_err());
        // Null passthrough
        assert!(rule.validate("status", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_date() {
        let rule = date();
        let data = json!({});

        // ISO date format
        assert!(rule
            .validate("birthday", &json!("2024-01-15"), &data)
            .is_ok());
        // RFC3339 datetime
        assert!(rule
            .validate("created", &json!("2024-01-15T10:30:00Z"), &data)
            .is_ok());
        // Invalid strings
        assert!(rule
            .validate("birthday", &json!("not-a-date"), &data)
            .is_err());
        assert!(rule
            .validate("birthday", &json!("2024-13-01"), &data)
            .is_err());
        // Non-string
        assert!(rule.validate("birthday", &json!(42), &data).is_err());
        // Null passthrough
        assert!(rule.validate("birthday", &json!(null), &data).is_ok());
    }

    #[test]
    fn test_nullable() {
        let rule = nullable();
        let data = json!({});

        // Nullable always passes - it's a marker rule
        assert!(rule.validate("field", &json!(null), &data).is_ok());
        assert!(rule.validate("field", &json!("value"), &data).is_ok());
        assert!(rule.validate("field", &json!(42), &data).is_ok());
        assert!(rule.validate("field", &json!(true), &data).is_ok());
    }

    #[test]
    fn test_accepted() {
        let rule = accepted();
        let data = json!({});

        // Accepted values
        assert!(rule.validate("terms", &json!(true), &data).is_ok());
        assert!(rule.validate("terms", &json!("yes"), &data).is_ok());
        assert!(rule.validate("terms", &json!("on"), &data).is_ok());
        assert!(rule.validate("terms", &json!("1"), &data).is_ok());
        assert!(rule.validate("terms", &json!("true"), &data).is_ok());
        assert!(rule.validate("terms", &json!(1), &data).is_ok());

        // Rejected values
        assert!(rule.validate("terms", &json!(false), &data).is_err());
        assert!(rule.validate("terms", &json!("no"), &data).is_err());
        assert!(rule.validate("terms", &json!("off"), &data).is_err());
        assert!(rule.validate("terms", &json!(0), &data).is_err());
        assert!(rule.validate("terms", &json!(null), &data).is_err());
        assert!(rule.validate("terms", &json!("false"), &data).is_err());
    }

    #[test]
    fn test_size_type_key_selection() {
        // String values use "string" subkey
        assert_eq!(
            get_size_type_key("min", &json!("hello")),
            "validation.min.string"
        );
        assert_eq!(
            get_size_type_key("max", &json!("hello")),
            "validation.max.string"
        );
        assert_eq!(
            get_size_type_key("between", &json!("hello")),
            "validation.between.string"
        );

        // Numeric values use "numeric" subkey
        assert_eq!(
            get_size_type_key("min", &json!(42)),
            "validation.min.numeric"
        );
        assert_eq!(
            get_size_type_key("max", &json!(42)),
            "validation.max.numeric"
        );
        assert_eq!(
            get_size_type_key("between", &json!(42)),
            "validation.between.numeric"
        );

        // Array values use "array" subkey
        assert_eq!(
            get_size_type_key("min", &json!([1, 2, 3])),
            "validation.min.array"
        );
        assert_eq!(
            get_size_type_key("max", &json!([1, 2, 3])),
            "validation.max.array"
        );
        assert_eq!(
            get_size_type_key("between", &json!([1, 2, 3])),
            "validation.between.array"
        );
    }
}