karbon_framework/validation/constraints/collection/
not_empty.rs1use crate::validation::constraints::{CollectionConstraint, ConstraintResult, ConstraintViolation};
2
3pub struct NotEmpty {
5 pub message: String,
6}
7
8impl Default for NotEmpty {
9 fn default() -> Self {
10 Self {
11 message: "This collection should not be empty.".to_string(),
12 }
13 }
14}
15
16impl NotEmpty {
17 pub fn new() -> Self {
18 Self::default()
19 }
20
21 pub fn with_message(mut self, message: impl Into<String>) -> Self {
22 self.message = message.into();
23 self
24 }
25}
26
27impl CollectionConstraint for NotEmpty {
28 fn validate_slice<T>(&self, value: &[T]) -> ConstraintResult {
29 if value.is_empty() {
30 return Err(ConstraintViolation::new(
31 self.name(),
32 &self.message,
33 "[]",
34 ));
35 }
36 Ok(())
37 }
38
39 fn name(&self) -> &'static str {
40 "NotEmpty"
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47
48 #[test]
49 fn test_not_empty() {
50 let constraint = NotEmpty::new();
51 assert!(constraint.validate_slice(&[1, 2, 3]).is_ok());
52 assert!(constraint.validate_slice(&["a"]).is_ok());
53 }
54
55 #[test]
56 fn test_empty() {
57 let constraint = NotEmpty::new();
58 assert!(constraint.validate_slice::<i32>(&[]).is_err());
59 }
60
61 #[test]
62 fn test_custom_message() {
63 let constraint = NotEmpty::new().with_message("Ajoutez au moins un élément.");
64 let err = constraint.validate_slice::<i32>(&[]).unwrap_err();
65 assert_eq!(err.message, "Ajoutez au moins un élément.");
66 }
67}