Skip to main content

karbon_framework/validation/constraints/comparison/
greater_than.rs

1use crate::validation::constraints::{ConstraintResult, ConstraintViolation, NumericConstraint};
2
3/// Validates that a value is greater than a given number.
4///
5/// Equivalent to Symfony's `GreaterThan` constraint.
6pub struct GreaterThan {
7    pub value: f64,
8    pub message: String,
9    pub or_equal: bool,
10}
11
12impl GreaterThan {
13    pub fn new(value: f64) -> Self {
14        Self {
15            value,
16            message: "This value should be greater than {{ compared_value }}.".to_string(),
17            or_equal: false,
18        }
19    }
20
21    /// GreaterThanOrEqual variant
22    pub fn or_equal(value: f64) -> Self {
23        Self {
24            value,
25            message: "This value should be greater than or equal to {{ compared_value }}."
26                .to_string(),
27            or_equal: true,
28        }
29    }
30
31    pub fn with_message(mut self, message: impl Into<String>) -> Self {
32        self.message = message.into();
33        self
34    }
35}
36
37impl NumericConstraint for GreaterThan {
38    fn validate_f64(&self, value: f64) -> ConstraintResult {
39        let valid = if self.or_equal {
40            value >= self.value
41        } else {
42            value > self.value
43        };
44
45        if !valid {
46            return Err(ConstraintViolation::new(
47                self.name(),
48                self.message
49                    .replace("{{ compared_value }}", &self.value.to_string()),
50                value.to_string(),
51            ));
52        }
53        Ok(())
54    }
55
56    fn name(&self) -> &'static str {
57        "GreaterThan"
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_greater_than() {
67        let constraint = GreaterThan::new(10.0);
68        assert!(constraint.validate_f64(11.0).is_ok());
69        assert!(constraint.validate_f64(100.0).is_ok());
70        assert!(constraint.validate_f64(10.0).is_err()); // not strictly greater
71        assert!(constraint.validate_f64(9.0).is_err());
72    }
73
74    #[test]
75    fn test_greater_than_or_equal() {
76        let constraint = GreaterThan::or_equal(10.0);
77        assert!(constraint.validate_f64(10.0).is_ok());
78        assert!(constraint.validate_f64(11.0).is_ok());
79        assert!(constraint.validate_f64(9.0).is_err());
80    }
81
82    #[test]
83    fn test_with_negative_values() {
84        let constraint = GreaterThan::new(-5.0);
85        assert!(constraint.validate_f64(0.0).is_ok());
86        assert!(constraint.validate_f64(-4.0).is_ok());
87        assert!(constraint.validate_f64(-6.0).is_err());
88    }
89}