json_model/attribute/
string_pattern.rs1use super::{AllowedType, Attribute};
2use crate::definition::Type;
3use crate::error::{Error, ValidationError};
4use crate::validator::{Context, DocumentPath, State};
5
6use std::collections::HashSet;
7
8use regex::Regex;
9
10#[derive(Debug)]
11pub struct StringPattern {
12 name: String,
13 re: Regex,
14}
15
16impl StringPattern {
17 pub fn new(mut path: DocumentPath, ctx: &Context) -> Result<Self, Error> {
18 let obj = ctx.raw_definition();
19
20 match Type::new(obj, path.clone())? {
21 Type::String => (),
22 typ => return Err(Error::ForbiddenType { path, typ }),
23 };
24
25 let re = match obj.get(ctx.name().as_str()) {
26 Some(pattern) => match pattern.as_str() {
27 Some(pattern_str) => match Regex::new(pattern_str) {
28 Ok(re) => re,
29 Err(_) => {
30 return Err(Error::InvalidValue {
31 path,
32 value: pattern.clone(),
33 })
34 }
35 },
36 None => {
37 path.add(ctx.name().as_str());
38 return Err(Error::InvalidValue {
39 path,
40 value: pattern.clone(),
41 });
42 }
43 },
44 None => {
45 return Err(Error::MissingAttribute {
46 path,
47 attr: ctx.name(),
48 })
49 }
50 };
51
52 Ok(StringPattern {
53 name: ctx.name(),
54 re,
55 })
56 }
57
58 pub fn allowed_types() -> HashSet<AllowedType> {
59 let mut set = HashSet::<AllowedType>::new();
60 set.insert(AllowedType::new(Type::String, false));
61 set
62 }
63
64 pub fn build(
65 _: &mut State,
66 path: DocumentPath,
67 ctx: &Context,
68 ) -> Result<Box<Attribute>, Error> {
69 Ok(Box::new(StringPattern::new(path, ctx)?))
70 }
71}
72
73impl Attribute for StringPattern {
74 fn validate(
75 &self,
76 _: &State,
77 path: Vec<String>,
78 input: &serde_json::Value,
79 ) -> Result<(), ValidationError> {
80 let val = match input.as_str() {
81 Some(val) => val,
82 None => {
83 return Err(ValidationError::Failure {
84 rule: "type".to_string(),
85 path: path,
86 message: "Value must be a string.".to_string(),
87 })
88 }
89 };
90 if !self.re.is_match(val) {
91 return Err(ValidationError::Failure {
92 rule: self.name.clone(),
93 path: path,
94 message: "Value does not match the required format.".to_string(),
95 });
96 }
97 Ok(())
98 }
99}