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