tanzim_validate/
non_empty.rs1use crate::error::{Error, ErrorKind};
2use crate::{Meta, Validator};
3use tanzim_value::{Value, ValueType};
4
5#[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 pub fn with_meta(mut self, meta: Meta) -> Self {
18 self.meta = meta;
19 self
20 }
21}
22
23impl Validator for NonEmpty {
24 fn meta(&self) -> &Meta {
25 &self.meta
26 }
27
28 fn meta_mut(&mut self) -> &mut Meta {
29 &mut self.meta
30 }
31
32 fn check(&self, value: &mut Value) -> Result<(), Error> {
33 let text = match value {
34 Value::String(text) => text,
35 other => {
36 return Err(Error::new(ErrorKind::Type {
37 expected: ValueType::String,
38 found: other.type_name(),
39 }));
40 }
41 };
42 if text.trim().is_empty() {
43 return Err(Error::new(ErrorKind::TooShort {
44 len: text.chars().count(),
45 min: 1,
46 }));
47 }
48 Ok(())
49 }
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn rejects_blank() {
58 assert!(
59 NonEmpty::new()
60 .validate(&mut Value::String("x".into()))
61 .is_ok()
62 );
63 assert!(
64 NonEmpty::new()
65 .validate(&mut Value::String(" ".into()))
66 .is_err()
67 );
68 }
69}