karbon_framework/validation/constraints/string/
not_blank.rs1use crate::validation::constraints::{Constraint, ConstraintResult, ConstraintViolation};
2
3pub struct NotBlank {
7 pub message: String,
8}
9
10impl Default for NotBlank {
11 fn default() -> Self {
12 Self {
13 message: "This value should not be blank.".to_string(),
14 }
15 }
16}
17
18impl NotBlank {
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 Constraint for NotBlank {
30 fn validate(&self, value: &str) -> ConstraintResult {
31 if value.trim().is_empty() {
32 return Err(ConstraintViolation::new(
33 self.name(),
34 &self.message,
35 value,
36 ));
37 }
38 Ok(())
39 }
40
41 fn name(&self) -> &'static str {
42 "NotBlank"
43 }
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49
50 #[test]
51 fn test_valid_values() {
52 let constraint = NotBlank::new();
53 assert!(constraint.validate("hello").is_ok());
54 assert!(constraint.validate("0").is_ok());
55 assert!(constraint.validate("false").is_ok());
56 assert!(constraint.validate(" a ").is_ok());
57 }
58
59 #[test]
60 fn test_blank_values() {
61 let constraint = NotBlank::new();
62 assert!(constraint.validate("").is_err());
63 assert!(constraint.validate(" ").is_err());
64 assert!(constraint.validate("\t").is_err());
65 assert!(constraint.validate("\n").is_err());
66 }
67
68 #[test]
69 fn test_custom_message() {
70 let constraint = NotBlank::new().with_message("Le champ est requis.");
71 let err = constraint.validate("").unwrap_err();
72 assert_eq!(err.message, "Le champ est requis.");
73 }
74}