valico/json_dsl/validators/
mutually_exclusive.rs

1use serde_json::{Value};
2
3use super::super::errors;
4
5pub struct MutuallyExclusive {
6    params: Vec<String>
7}
8
9impl MutuallyExclusive {
10    pub fn new(params: &[&str]) -> MutuallyExclusive {
11        MutuallyExclusive {
12            params: params.iter().map(|s| s.to_string()).collect()
13        }
14    }
15}
16
17impl super::Validator for MutuallyExclusive {
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        if matched.len() <= 1 {
28            Ok(())
29        } else {
30            Err(vec![
31                Box::new(errors::MutuallyExclusive{
32                    path: path.to_string(),
33                    params: matched,
34                    detail: Some("Fields are mutually exclusive".to_string())
35                })
36            ])
37        }
38    }
39}