Skip to main content

karbon_framework/validation/constraints/comparison/
not_equal_to.rs

1use crate::validation::constraints::{Constraint, ConstraintResult, ConstraintViolation};
2
3/// Validates that a value is not equal to a given value.
4///
5/// Equivalent to Symfony's `NotEqualTo` constraint.
6pub struct NotEqualTo {
7    pub value: String,
8    pub message: String,
9}
10
11impl NotEqualTo {
12    pub fn new(value: impl Into<String>) -> Self {
13        Self {
14            value: value.into(),
15            message: "This value should not be equal to {{ compared_value }}.".to_string(),
16        }
17    }
18
19    pub fn with_message(mut self, message: impl Into<String>) -> Self {
20        self.message = message.into();
21        self
22    }
23}
24
25impl Constraint for NotEqualTo {
26    fn validate(&self, value: &str) -> ConstraintResult {
27        if value == self.value {
28            return Err(ConstraintViolation::new(
29                self.name(),
30                self.message.replace("{{ compared_value }}", &self.value),
31                value,
32            ));
33        }
34        Ok(())
35    }
36
37    fn name(&self) -> &'static str {
38        "NotEqualTo"
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45
46    #[test]
47    fn test_different_values() {
48        let constraint = NotEqualTo::new("forbidden");
49        assert!(constraint.validate("allowed").is_ok());
50        assert!(constraint.validate("").is_ok());
51    }
52
53    #[test]
54    fn test_same_value() {
55        let constraint = NotEqualTo::new("forbidden");
56        assert!(constraint.validate("forbidden").is_err());
57    }
58}