Skip to main content

valico/json_dsl/validators/
mod.rs

1use serde_json::Value;
2use std::fmt;
3
4use crate::common::error;
5
6pub use self::allowed_values::AllowedValues;
7pub use self::at_least_one_of::AtLeastOneOf;
8pub use self::exactly_one_of::ExactlyOneOf;
9pub use self::mutually_exclusive::MutuallyExclusive;
10pub use self::rejected_values::RejectedValues;
11
12macro_rules! strict_process {
13    ($val:expr, $path:ident, $err:expr) => {{
14        let maybe_val = $val;
15        if maybe_val.is_none() {
16            return Err(vec![Box::new($crate::json_dsl::errors::WrongType {
17                path: $path.to_string(),
18                detail: $err.to_string(),
19            })]);
20        }
21
22        maybe_val.unwrap()
23    }};
24}
25
26mod allowed_values;
27mod at_least_one_of;
28mod exactly_one_of;
29mod mutually_exclusive;
30mod regex;
31mod rejected_values;
32
33pub type ValidatorResult = Result<(), error::ValicoErrors>;
34
35pub trait Validator {
36    fn validate(&self, item: &Value, _: &str) -> ValidatorResult;
37}
38
39impl fmt::Debug for dyn Validator + 'static {
40    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
41        fmt.write_str("[validator]")
42    }
43}
44
45pub type BoxedValidator = Box<dyn Validator + 'static + Send + Sync>;
46pub type Validators = Vec<BoxedValidator>;
47
48impl<T> Validator for T
49where
50    T: Fn(&Value, &str) -> ValidatorResult,
51{
52    fn validate(&self, val: &Value, path: &str) -> ValidatorResult {
53        self(val, path)
54    }
55}