Skip to main content

tanzim_validate/
regex.rs

1use crate::error::{Error, ErrorKind};
2use crate::{Meta, Validator};
3use tanzim_value::{Value, ValueType};
4
5/// (`regex` feature) Accepts a string that is itself a valid regular expression.
6#[derive(Debug, Clone, Default)]
7pub struct RegexPattern {
8    meta: Meta,
9}
10
11impl RegexPattern {
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!(RegexPattern);
24
25impl Validator for RegexPattern {
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        match regex::Regex::new(text) {
45            Ok(_) => Ok(()),
46            Err(_) => Err(Error::new(ErrorKind::Format {
47                expected: "regular expression",
48            })),
49        }
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn accepts_valid_and_rejects_invalid() {
59        assert!(
60            RegexPattern::new()
61                .validate(&mut Value::String("^a.*$".into()))
62                .is_ok()
63        );
64        assert!(
65            RegexPattern::new()
66                .validate(&mut Value::String("(".into()))
67                .is_err()
68        );
69    }
70}