serenade_validator/
constraint.rs1use crate::ConstraintViolationList;
4
5pub trait Constraint: Send + Sync {
7 fn code(&self) -> &'static str;
9
10 fn validate(&self, value: &str, property_path: &str, violations: &mut ConstraintViolationList);
12}
13
14#[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#[derive(Debug, Clone, Copy)]
36pub struct Length {
37 pub min: usize,
39 pub max: usize,
41}
42
43impl Length {
44 #[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#[derive(Debug, Clone, Copy)]
73pub struct Range {
74 pub min: i64,
76 pub max: i64,
78}
79
80impl Range {
81 #[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}