Skip to main content

tanzim_validate/
non_empty.rs

1use crate::error::{Error, ErrorKind};
2use crate::{Meta, Validator};
3use tanzim_value::{Value, ValueType};
4
5/// (`non_empty` feature) Accepts a non-blank string (at least one non-whitespace character).
6#[derive(Debug, Clone, Default)]
7pub struct NonEmpty {
8    meta: Meta,
9}
10
11impl NonEmpty {
12    pub fn new() -> Self {
13        Self::default()
14    }
15
16    /// Attach human-facing metadata (name, description, examples, default, output conversion).
17    pub fn with_meta(mut self, meta: Meta) -> Self {
18        self.meta = meta;
19        self
20    }
21}
22
23crate::impl_meta_methods!(NonEmpty);
24
25impl Validator for NonEmpty {
26    fn meta(&self) -> &Meta {
27        &self.meta
28    }
29
30    fn meta_mut(&mut self) -> &mut Meta {
31        &mut self.meta
32    }
33
34    fn check(&self, value: &mut Value) -> Result<(), Error> {
35        let text = match value {
36            Value::String(text) => text,
37            other => {
38                return Err(Error::new(ErrorKind::Type {
39                    expected: ValueType::String,
40                    found: other.type_name(),
41                }));
42            }
43        };
44        if text.trim().is_empty() {
45            return Err(Error::new(ErrorKind::TooShort {
46                len: text.chars().count(),
47                min: 1,
48            }));
49        }
50        Ok(())
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn rejects_blank() {
60        assert!(
61            NonEmpty::new()
62                .validate(&mut Value::String("x".into()))
63                .is_ok()
64        );
65        assert!(
66            NonEmpty::new()
67                .validate(&mut Value::String("   ".into()))
68                .is_err()
69        );
70    }
71}