karbon_framework/validation/constraints/comparison/
equal_to.rs1use crate::validation::constraints::{Constraint, ConstraintResult, ConstraintViolation};
2
3pub struct EqualTo {
7 pub value: String,
8 pub message: String,
9}
10
11impl EqualTo {
12 pub fn new(value: impl Into<String>) -> Self {
13 Self {
14 value: value.into(),
15 message: "This value should 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 EqualTo {
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 "EqualTo"
39 }
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 #[test]
47 fn test_equal_values() {
48 let constraint = EqualTo::new("hello");
49 assert!(constraint.validate("hello").is_ok());
50 }
51
52 #[test]
53 fn test_not_equal_values() {
54 let constraint = EqualTo::new("hello");
55 assert!(constraint.validate("world").is_err());
56 assert!(constraint.validate("Hello").is_err()); assert!(constraint.validate("").is_err());
58 }
59
60 #[test]
61 fn test_error_message() {
62 let constraint = EqualTo::new("expected");
63 let err = constraint.validate("actual").unwrap_err();
64 assert!(err.message.contains("expected"));
65 }
66}