valico/json_dsl/validators/
exactly_one_of.rs
1use serde_json::{Value};
2
3use super::super::errors;
4
5pub struct ExactlyOneOf {
6 params: Vec<String>
7}
8
9impl ExactlyOneOf {
10 pub fn new(params: &[&str]) -> ExactlyOneOf {
11 ExactlyOneOf {
12 params: params.iter().map(|s| s.to_string()).collect()
13 }
14 }
15}
16
17impl super::Validator for ExactlyOneOf {
18 fn validate(&self, val: &Value, path: &str) -> super::ValidatorResult {
19
20 let object = strict_process!(val.as_object(), path, "The value must be an object");
21
22 let mut matched = vec![];
23 for param in self.params.iter() {
24 if object.contains_key(param) { matched.push(param.clone()); }
25 }
26
27 let len = matched.len();
28 if len == 1 {
29 Ok(())
30 } else if len > 1 {
31 Err(vec![
32 Box::new(errors::ExactlyOne {
33 path: path.to_string(),
34 detail: Some("Exactly one is allowed at one time".to_string()),
35 params: matched
36 })
37 ])
38 } else {
39 Err(vec![
40 Box::new(errors::ExactlyOne {
41 path: path.to_string(),
42 detail: Some("Exactly one must be present".to_string()),
43 params: self.params.clone()
44 })
45 ])
46 }
47 }
48}