garde/rules/
matches.rs

1//! Field matching validation.
2//!
3//! ```rust
4//! #[derive(garde::Validate)]
5//! struct Test {
6//!     #[garde(skip)]
7//!     foo: String,
8//!     #[garde(matches(foo))]
9//!     bar: String,
10//! }
11//! ```
12//!
13//! The entrypoint is the [`Matches`] trait. Implementing this trait for a type allows that type to be used with the `#[garde(matches)]` rule.
14//!
15//! This trait has a blanket implementation for all `T: PartialEq<O>, O`.
16
17use crate::Error;
18
19pub fn apply<T: Matches<O>, O>(v: &T, (field, value): (&str, &O)) -> Result<(), Error> {
20    if !v.validate_matches(value) {
21        return Err(Error::new(format!("does not match {field} field")));
22    }
23    Ok(())
24}
25
26pub trait Matches<O> {
27    fn validate_matches(&self, other: &O) -> bool;
28}
29
30impl<T: PartialEq<O>, O> Matches<O> for T {
31    fn validate_matches(&self, other: &O) -> bool {
32        self.eq(other)
33    }
34}