valico/json_dsl/validators/
mutually_exclusive.rs1use 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 let object = strict_process!(val.as_object(), path, "The value must be an object");
20
21 let mut matched = vec![];
22 for param in self.params.iter() {
23 if object.contains_key(param) {
24 matched.push(param.clone());
25 }
26 }
27
28 if matched.len() <= 1 {
29 Ok(())
30 } else {
31 Err(vec![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}