Skip to main content

serenade_validator/
constraint.rs

1//! Constraint trait and built-in constraints.
2
3use crate::ConstraintViolationList;
4
5/// A rule that may append violations for a value.
6pub trait Constraint: Send + Sync {
7    /// Stable constraint code (for example `NotBlank`).
8    fn code(&self) -> &'static str;
9
10    /// Validates `value` for `property_path`, appending to `violations` on failure.
11    fn validate(&self, value: &str, property_path: &str, violations: &mut ConstraintViolationList);
12}
13
14/// Rejects empty or whitespace-only strings.
15#[derive(Debug, Default, Clone, Copy)]
16pub struct NotBlank;
17
18impl Constraint for NotBlank {
19    fn code(&self) -> &'static str {
20        "NotBlank"
21    }
22
23    fn validate(&self, value: &str, property_path: &str, violations: &mut ConstraintViolationList) {
24        if value.trim().is_empty() {
25            violations.add(crate::Violation::new(
26                property_path,
27                "This value should not be blank.",
28                self.code(),
29            ));
30        }
31    }
32}
33
34/// Enforces a string length range (inclusive).
35#[derive(Debug, Clone, Copy)]
36pub struct Length {
37    /// Minimum length (inclusive).
38    pub min: usize,
39    /// Maximum length (inclusive).
40    pub max: usize,
41}
42
43impl Length {
44    /// Creates a length constraint.
45    #[must_use]
46    pub const fn new(min: usize, max: usize) -> Self {
47        Self { min, max }
48    }
49}
50
51impl Constraint for Length {
52    fn code(&self) -> &'static str {
53        "Length"
54    }
55
56    fn validate(&self, value: &str, property_path: &str, violations: &mut ConstraintViolationList) {
57        let len = value.chars().count();
58        if len < self.min || len > self.max {
59            violations.add(crate::Violation::new(
60                property_path,
61                format!(
62                    "This value should have between {} and {} characters.",
63                    self.min, self.max
64                ),
65                self.code(),
66            ));
67        }
68    }
69}
70
71/// Enforces an inclusive numeric range for a parsed `i64`.
72#[derive(Debug, Clone, Copy)]
73pub struct Range {
74    /// Minimum value (inclusive).
75    pub min: i64,
76    /// Maximum value (inclusive).
77    pub max: i64,
78}
79
80impl Range {
81    /// Creates a range constraint.
82    #[must_use]
83    pub const fn new(min: i64, max: i64) -> Self {
84        Self { min, max }
85    }
86}
87
88impl Constraint for Range {
89    fn code(&self) -> &'static str {
90        "Range"
91    }
92
93    fn validate(&self, value: &str, property_path: &str, violations: &mut ConstraintViolationList) {
94        let Ok(parsed) = value.parse::<i64>() else {
95            violations.add(crate::Violation::new(
96                property_path,
97                "This value should be a valid integer.",
98                self.code(),
99            ));
100            return;
101        };
102        if parsed < self.min || parsed > self.max {
103            violations.add(crate::Violation::new(
104                property_path,
105                format!(
106                    "This value should be between {} and {}.",
107                    self.min, self.max
108                ),
109                self.code(),
110            ));
111        }
112    }
113}