karbon_framework/validation/constraints/number/
negative.rs1use crate::validation::constraints::{ConstraintResult, ConstraintViolation, NumericConstraint};
2
3pub struct Negative {
7 pub message: String,
8}
9
10impl Default for Negative {
11 fn default() -> Self {
12 Self {
13 message: "This value should be negative.".to_string(),
14 }
15 }
16}
17
18impl Negative {
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 Negative {
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 "Negative"
43 }
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49
50 #[test]
51 fn test_negative_values() {
52 let constraint = Negative::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_negative_values() {
60 let constraint = Negative::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}