Skip to main content

karbon_framework/validation/constraints/number/
positive.rs

1use crate::validation::constraints::{ConstraintResult, ConstraintViolation, NumericConstraint};
2
3/// Validates that a value is a positive number (strictly greater than zero).
4///
5/// Equivalent to Symfony's `Positive` constraint.
6pub struct Positive {
7    pub message: String,
8}
9
10impl Default for Positive {
11    fn default() -> Self {
12        Self {
13            message: "This value should be positive.".to_string(),
14        }
15    }
16}
17
18impl Positive {
19    pub fn new() -> Self {
20        Self::default()
21    }
22
23    pub fn with_message(mut self, message: impl Into<String>) -> Self {
24        self.message = message.into();
25        self
26    }
27}
28
29impl NumericConstraint for Positive {
30    fn validate_f64(&self, value: f64) -> ConstraintResult {
31        if value <= 0.0 {
32            return Err(ConstraintViolation::new(
33                self.name(),
34                &self.message,
35                value.to_string(),
36            ));
37        }
38        Ok(())
39    }
40
41    fn name(&self) -> &'static str {
42        "Positive"
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn test_positive_values() {
52        let constraint = Positive::new();
53        assert!(constraint.validate_f64(1.0).is_ok());
54        assert!(constraint.validate_f64(0.001).is_ok());
55        assert!(constraint.validate_f64(1000.0).is_ok());
56    }
57
58    #[test]
59    fn test_non_positive_values() {
60        let constraint = Positive::new();
61        assert!(constraint.validate_f64(0.0).is_err());
62        assert!(constraint.validate_f64(-1.0).is_err());
63        assert!(constraint.validate_f64(-0.001).is_err());
64    }
65}