validator/
traits.rs

1use crate::types::ValidationErrors;
2
3/// This is the original trait that was implemented by deriving `Validate`. It will still be
4/// implemented for struct validations that don't take custom arguments. The call is being
5/// forwarded to the `ValidateArgs<'v_a>` trait.
6pub trait Validate {
7    fn validate(&self) -> Result<(), ValidationErrors>;
8}
9
10impl<T: Validate> Validate for &T {
11    fn validate(&self) -> Result<(), ValidationErrors> {
12        T::validate(self)
13    }
14}
15
16/// This trait will be implemented by deriving `Validate`. This implementation can take one
17/// argument and pass this on to custom validators. The default `Args` type will be `()` if
18/// there is no custom validation with defined arguments.
19///
20/// The `Args` type can use the lifetime `'v_a` to pass references onto the validator.
21pub trait ValidateArgs<'v_a> {
22    type Args;
23    fn validate_with_args(&self, args: Self::Args) -> Result<(), ValidationErrors>;
24}
25
26impl<'v_a, T, U> ValidateArgs<'v_a> for Option<T>
27    where
28        T: ValidateArgs<'v_a, Args=U>,
29{
30    type Args = U;
31
32    fn validate_with_args(&self, args: Self::Args) -> Result<(), ValidationErrors> {
33        if let Some(nested) = self {
34            T::validate_with_args(nested, args)
35        } else {
36            Ok(())
37        }
38    }
39}