rustapi-validate 0.1.450

Type-safe request validation for RustAPI. Wrapper around the `validator` crate with deep framework integration.
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
//! Synchronous validation rules.
//!
//! These rules perform validation without requiring async operations.

use crate::v2::error::RuleError;
use crate::v2::traits::ValidationRule;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::sync::OnceLock;

// Pre-compiled regex patterns
static EMAIL_REGEX: OnceLock<Regex> = OnceLock::new();
static URL_REGEX: OnceLock<Regex> = OnceLock::new();
static PHONE_REGEX: OnceLock<Regex> = OnceLock::new();

fn email_regex() -> &'static Regex {
    EMAIL_REGEX.get_or_init(|| {
        // RFC 5322 simplified email regex
        Regex::new(
            r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
        ).unwrap()
    })
}

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

fn phone_regex() -> &'static Regex {
    // E.164 format (e.g. +14155552671)
    PHONE_REGEX.get_or_init(|| Regex::new(r"^\+[1-9]\d{1,14}$").unwrap())
}

/// Email format validation rule.
///
/// Validates that a string is a valid email address according to RFC 5322.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct EmailRule {
    /// Custom error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl EmailRule {
    /// Create a new email rule with default message.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create an email rule with a custom message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

impl ValidationRule<str> for EmailRule {
    fn validate(&self, value: &str) -> Result<(), RuleError> {
        if email_regex().is_match(value) {
            Ok(())
        } else {
            let message = self
                .message
                .clone()
                .unwrap_or_else(|| "validation.email.invalid".to_string());
            Err(RuleError::new("email", message))
        }
    }

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

impl ValidationRule<String> for EmailRule {
    fn validate(&self, value: &String) -> Result<(), RuleError> {
        <Self as ValidationRule<str>>::validate(self, value.as_str())
    }

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

/// String length validation rule.
///
/// Validates that a string's length is within specified bounds.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LengthRule {
    /// Minimum length (inclusive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min: Option<usize>,
    /// Maximum length (inclusive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max: Option<usize>,
    /// Custom error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl LengthRule {
    /// Create a length rule with min and max bounds.
    pub fn new(min: usize, max: usize) -> Self {
        Self {
            min: Some(min),
            max: Some(max),
            message: None,
        }
    }

    /// Create a length rule with only a minimum.
    pub fn min(min: usize) -> Self {
        Self {
            min: Some(min),
            max: None,
            message: None,
        }
    }

    /// Create a length rule with only a maximum.
    pub fn max(max: usize) -> Self {
        Self {
            min: None,
            max: Some(max),
            message: None,
        }
    }

    /// Set a custom error message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

impl ValidationRule<str> for LengthRule {
    fn validate(&self, value: &str) -> Result<(), RuleError> {
        let len = value.chars().count();

        if let Some(min) = self.min {
            if len < min {
                let message = self
                    .message
                    .clone()
                    .unwrap_or_else(|| "validation.length.min".to_string());
                return Err(RuleError::new("length", message)
                    .param("min", min)
                    .param("max", self.max)
                    .param("actual", len));
            }
        }

        if let Some(max) = self.max {
            if len > max {
                let message = self
                    .message
                    .clone()
                    .unwrap_or_else(|| "validation.length.max".to_string());
                return Err(RuleError::new("length", message)
                    .param("min", self.min)
                    .param("max", max)
                    .param("actual", len));
            }
        }

        Ok(())
    }

    fn rule_name(&self) -> &'static str {
        "length"
    }
}

impl ValidationRule<String> for LengthRule {
    fn validate(&self, value: &String) -> Result<(), RuleError> {
        <Self as ValidationRule<str>>::validate(self, value.as_str())
    }

    fn rule_name(&self) -> &'static str {
        "length"
    }
}

/// Numeric range validation rule.
///
/// Validates that a number is within specified bounds.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RangeRule<T> {
    /// Minimum value (inclusive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min: Option<T>,
    /// Maximum value (inclusive)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max: Option<T>,
    /// Custom error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl<T> RangeRule<T> {
    /// Create a range rule with min and max bounds.
    pub fn new(min: T, max: T) -> Self {
        Self {
            min: Some(min),
            max: Some(max),
            message: None,
        }
    }

    /// Create a range rule with only a minimum.
    pub fn min(min: T) -> Self {
        Self {
            min: Some(min),
            max: None,
            message: None,
        }
    }

    /// Create a range rule with only a maximum.
    pub fn max(max: T) -> Self {
        Self {
            min: None,
            max: Some(max),
            message: None,
        }
    }

    /// Set a custom error message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

impl<T> ValidationRule<T> for RangeRule<T>
where
    T: PartialOrd + std::fmt::Display + Copy + Send + Sync + std::fmt::Debug + Serialize,
{
    fn validate(&self, value: &T) -> Result<(), RuleError> {
        if let Some(ref min) = self.min {
            if value < min {
                let message = self
                    .message
                    .clone()
                    .unwrap_or_else(|| "validation.range.min".to_string());
                return Err(RuleError::new("range", message)
                    .param("min", *min)
                    .param("max", self.max)
                    .param("actual", *value));
            }
        }

        if let Some(ref max) = self.max {
            if value > max {
                let message = self
                    .message
                    .clone()
                    .unwrap_or_else(|| "validation.range.max".to_string());
                return Err(RuleError::new("range", message)
                    .param("min", self.min)
                    .param("max", *max)
                    .param("actual", *value));
            }
        }

        Ok(())
    }

    fn rule_name(&self) -> &'static str {
        "range"
    }
}

/// Regex pattern validation rule.
///
/// Validates that a string matches a regex pattern.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegexRule {
    /// The regex pattern
    pub pattern: String,
    /// Compiled regex (not serialized)
    #[serde(skip)]
    compiled: OnceLock<Result<Regex, String>>,
    /// Custom error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl PartialEq for RegexRule {
    fn eq(&self, other: &Self) -> bool {
        self.pattern == other.pattern && self.message == other.message
    }
}

impl RegexRule {
    /// Create a new regex rule.
    pub fn new(pattern: impl Into<String>) -> Self {
        Self {
            pattern: pattern.into(),
            compiled: OnceLock::new(),
            message: None,
        }
    }

    /// Set a custom error message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }

    fn get_regex(&self) -> Result<&Regex, RuleError> {
        let result = self.compiled.get_or_init(|| {
            Regex::new(&self.pattern)
                .map_err(|_| format!("Invalid regex pattern: {}", self.pattern))
        });

        match result {
            Ok(regex) => Ok(regex),
            Err(msg) => Err(RuleError::new("regex", msg.clone())),
        }
    }
}

impl ValidationRule<str> for RegexRule {
    fn validate(&self, value: &str) -> Result<(), RuleError> {
        let regex = self.get_regex()?;

        if regex.is_match(value) {
            Ok(())
        } else {
            let message = self
                .message
                .clone()
                .unwrap_or_else(|| "validation.regex.mismatch".to_string());
            Err(RuleError::new("regex", message).param("pattern", self.pattern.clone()))
        }
    }

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

impl ValidationRule<String> for RegexRule {
    fn validate(&self, value: &String) -> Result<(), RuleError> {
        <Self as ValidationRule<str>>::validate(self, value.as_str())
    }

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

/// URL format validation rule.
///
/// Validates that a string is a valid URL.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct UrlRule {
    /// Custom error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl UrlRule {
    /// Create a new URL rule.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a URL rule with a custom message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

impl ValidationRule<str> for UrlRule {
    fn validate(&self, value: &str) -> Result<(), RuleError> {
        if url_regex().is_match(value) {
            Ok(())
        } else {
            let message = self
                .message
                .clone()
                .unwrap_or_else(|| "validation.url.invalid".to_string());
            Err(RuleError::new("url", message))
        }
    }

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

impl ValidationRule<String> for UrlRule {
    fn validate(&self, value: &String) -> Result<(), RuleError> {
        <Self as ValidationRule<str>>::validate(self, value.as_str())
    }

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

/// Required (non-empty) validation rule.
///
/// Validates that a value is not empty.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct RequiredRule {
    /// Custom error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl RequiredRule {
    /// Create a new required rule.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a required rule with a custom message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

impl ValidationRule<str> for RequiredRule {
    fn validate(&self, value: &str) -> Result<(), RuleError> {
        if !value.trim().is_empty() {
            Ok(())
        } else {
            let message = self
                .message
                .clone()
                .unwrap_or_else(|| "validation.required.missing".to_string());
            Err(RuleError::new("required", message))
        }
    }

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

impl ValidationRule<String> for RequiredRule {
    fn validate(&self, value: &String) -> Result<(), RuleError> {
        <Self as ValidationRule<str>>::validate(self, value.as_str())
    }

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

impl<T> ValidationRule<Option<T>> for RequiredRule
where
    T: std::fmt::Debug + Send + Sync,
{
    fn validate(&self, value: &Option<T>) -> Result<(), RuleError> {
        if value.is_some() {
            Ok(())
        } else {
            let message = self
                .message
                .clone()
                .unwrap_or_else(|| "validation.required.missing".to_string());
            Err(RuleError::new("required", message))
        }
    }

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

/// Credit Card validation rule (Luhn algorithm).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct CreditCardRule {
    /// Custom error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl CreditCardRule {
    /// Create a new credit card rule.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set a custom error message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

impl ValidationRule<str> for CreditCardRule {
    fn validate(&self, value: &str) -> Result<(), RuleError> {
        let mut sum = 0;
        let mut double = false;

        // Iterate over digits in reverse
        for c in value.chars().rev() {
            if !c.is_ascii_digit() {
                let message = self
                    .message
                    .clone()
                    .unwrap_or_else(|| "validation.credit_card.invalid_format".to_string());
                return Err(RuleError::new("credit_card", message));
            }

            let mut digit = c.to_digit(10).unwrap();

            if double {
                digit *= 2;
                if digit > 9 {
                    digit -= 9;
                }
            }

            sum += digit;
            double = !double;
        }

        if sum > 0 && sum % 10 == 0 {
            Ok(())
        } else {
            let message = self
                .message
                .clone()
                .unwrap_or_else(|| "validation.credit_card.invalid".to_string());
            Err(RuleError::new("credit_card", message))
        }
    }

    fn rule_name(&self) -> &'static str {
        "credit_card"
    }
}

impl ValidationRule<String> for CreditCardRule {
    fn validate(&self, value: &String) -> Result<(), RuleError> {
        <Self as ValidationRule<str>>::validate(self, value.as_str())
    }

    fn rule_name(&self) -> &'static str {
        "credit_card"
    }
}

/// IP Address validation rule (IPv4 and IPv6).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct IpRule {
    /// Check for IPv4 only
    #[serde(skip_serializing_if = "Option::is_none")]
    pub v4: Option<bool>,
    /// Check for IPv6 only
    #[serde(skip_serializing_if = "Option::is_none")]
    pub v6: Option<bool>,
    /// Custom error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl IpRule {
    /// Create a new IP rule (accepts both v4 and v6).
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a rule for IPv4 only.
    pub fn v4() -> Self {
        Self {
            v4: Some(true),
            v6: None,
            message: None,
        }
    }

    /// Create a rule for IPv6 only.
    pub fn v6() -> Self {
        Self {
            v4: None,
            v6: Some(true),
            message: None,
        }
    }

    /// Set a custom error message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

impl ValidationRule<str> for IpRule {
    fn validate(&self, value: &str) -> Result<(), RuleError> {
        use std::net::IpAddr;

        match value.parse::<IpAddr>() {
            Ok(ip) => {
                if let Some(true) = self.v4 {
                    if !ip.is_ipv4() {
                        let message = self
                            .message
                            .clone()
                            .unwrap_or_else(|| "validation.ip.v4_required".to_string());
                        return Err(RuleError::new("ip", message));
                    }
                }
                if let Some(true) = self.v6 {
                    if !ip.is_ipv6() {
                        let message = self
                            .message
                            .clone()
                            .unwrap_or_else(|| "validation.ip.v6_required".to_string());
                        return Err(RuleError::new("ip", message));
                    }
                }
                Ok(())
            }
            Err(_) => {
                let message = self
                    .message
                    .clone()
                    .unwrap_or_else(|| "validation.ip.invalid".to_string());
                Err(RuleError::new("ip", message))
            }
        }
    }

    fn rule_name(&self) -> &'static str {
        "ip"
    }
}

impl ValidationRule<String> for IpRule {
    fn validate(&self, value: &String) -> Result<(), RuleError> {
        <Self as ValidationRule<str>>::validate(self, value.as_str())
    }

    fn rule_name(&self) -> &'static str {
        "ip"
    }
}

/// Phone number validation rule (E.164).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct PhoneRule {
    /// Custom error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl PhoneRule {
    /// Create a new phone rule.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set a custom error message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

impl ValidationRule<str> for PhoneRule {
    fn validate(&self, value: &str) -> Result<(), RuleError> {
        if phone_regex().is_match(value) {
            Ok(())
        } else {
            let message = self
                .message
                .clone()
                .unwrap_or_else(|| "validation.phone.invalid".to_string());
            Err(RuleError::new("phone", message))
        }
    }

    fn rule_name(&self) -> &'static str {
        "phone"
    }
}

impl ValidationRule<String> for PhoneRule {
    fn validate(&self, value: &String) -> Result<(), RuleError> {
        <Self as ValidationRule<str>>::validate(self, value.as_str())
    }

    fn rule_name(&self) -> &'static str {
        "phone"
    }
}

/// Contains substring validation rule.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ContainsRule {
    /// The substring that must be present
    pub needle: String,
    /// Custom error message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl ContainsRule {
    /// Create a new contains rule.
    pub fn new(needle: impl Into<String>) -> Self {
        Self {
            needle: needle.into(),
            message: None,
        }
    }

    /// Set a custom error message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());
        self
    }
}

impl ValidationRule<str> for ContainsRule {
    fn validate(&self, value: &str) -> Result<(), RuleError> {
        if value.contains(&self.needle) {
            Ok(())
        } else {
            let message = self
                .message
                .clone()
                .unwrap_or_else(|| "validation.contains.missing".to_string());
            Err(RuleError::new("contains", message).param("needle", self.needle.clone()))
        }
    }

    fn rule_name(&self) -> &'static str {
        "contains"
    }
}

impl ValidationRule<String> for ContainsRule {
    fn validate(&self, value: &String) -> Result<(), RuleError> {
        <Self as ValidationRule<str>>::validate(self, value.as_str())
    }

    fn rule_name(&self) -> &'static str {
        "contains"
    }
}

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

    #[test]
    fn email_rule_valid() {
        let rule = EmailRule::new();
        assert!(rule.validate("test@example.com").is_ok());
        assert!(rule.validate("user.name+tag@domain.co.uk").is_ok());
    }

    #[test]
    fn email_rule_invalid() {
        let rule = EmailRule::new();
        assert!(rule.validate("invalid").is_err());
        assert!(rule.validate("@domain.com").is_err());
        assert!(rule.validate("user@").is_err());
    }

    #[test]
    fn email_rule_custom_message() {
        let rule = EmailRule::new().with_message("Please enter a valid email");
        let err = rule.validate("invalid").unwrap_err();
        assert_eq!(err.message, "Please enter a valid email");
    }

    #[test]
    fn length_rule_valid() {
        let rule = LengthRule::new(3, 10);
        assert!(rule.validate("abc").is_ok());
        assert!(rule.validate("abcdefghij").is_ok());
    }

    #[test]
    fn length_rule_too_short() {
        let rule = LengthRule::new(3, 10);
        let err = rule.validate("ab").unwrap_err();
        assert_eq!(err.code, "length");
    }

    #[test]
    fn length_rule_too_long() {
        let rule = LengthRule::new(3, 10);
        let err = rule.validate("abcdefghijk").unwrap_err();
        assert_eq!(err.code, "length");
    }

    #[test]
    fn range_rule_valid() {
        let rule = RangeRule::new(18, 120);
        assert!(rule.validate(&18).is_ok());
        assert!(rule.validate(&50).is_ok());
        assert!(rule.validate(&120).is_ok());
    }

    #[test]
    fn range_rule_too_low() {
        let rule = RangeRule::new(18, 120);
        let err = rule.validate(&17).unwrap_err();
        assert_eq!(err.code, "range");
    }

    #[test]
    fn range_rule_too_high() {
        let rule = RangeRule::new(18, 120);
        let err = rule.validate(&121).unwrap_err();
        assert_eq!(err.code, "range");
    }

    #[test]
    fn regex_rule_valid() {
        let rule = RegexRule::new(r"^\d{3}-\d{4}$");
        assert!(rule.validate("123-4567").is_ok());
    }

    #[test]
    fn regex_rule_invalid() {
        let rule = RegexRule::new(r"^\d{3}-\d{4}$");
        assert!(rule.validate("1234567").is_err());
    }

    #[test]
    fn url_rule_valid() {
        let rule = UrlRule::new();
        assert!(rule.validate("https://example.com").is_ok());
        assert!(rule.validate("http://example.com/path?query=1").is_ok());
    }

    #[test]
    fn url_rule_invalid() {
        let rule = UrlRule::new();
        assert!(rule.validate("not-a-url").is_err());
        assert!(rule.validate("ftp://").is_err());
    }

    #[test]
    fn required_rule_valid() {
        let rule = RequiredRule::new();
        assert!(rule.validate("value").is_ok());
        assert!(rule.validate("  value  ").is_ok());
    }

    #[test]
    fn required_rule_empty() {
        let rule = RequiredRule::new();
        assert!(rule.validate("").is_err());
        assert!(rule.validate("   ").is_err());
    }

    #[test]
    fn required_rule_option() {
        let rule = RequiredRule::new();
        assert!(ValidationRule::<Option<i32>>::validate(&rule, &Some(42)).is_ok());
        assert!(ValidationRule::<Option<i32>>::validate(&rule, &None).is_err());
    }

    #[test]
    fn rule_serialization_roundtrip() {
        let rule = LengthRule::new(3, 50).with_message("Custom message");
        let json = serde_json::to_string(&rule).unwrap();
        let parsed: LengthRule = serde_json::from_str(&json).unwrap();
        assert_eq!(rule, parsed);
    }
}