From f51e0d671880b32a574060c642e405c590dd0974 Mon Sep 17 00:00:00 2001 From: Lucas Pickering Date: Wed, 20 May 2020 07:48:37 -0400 Subject: Add a blanket Validate implementation for references --- validator/src/traits.rs | 6 ++++++ validator_derive/tests/range.rs | 21 ++++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/validator/src/traits.rs b/validator/src/traits.rs index 61bb002..93b23fa 100644 --- a/validator/src/traits.rs +++ b/validator/src/traits.rs @@ -93,3 +93,9 @@ impl<'a, S, H: ::std::hash::BuildHasher> Contains for &'a HashMap pub trait Validate { fn validate(&self) -> Result<(), ValidationErrors>; } + +impl Validate for &T { + fn validate(&self) -> Result<(), ValidationErrors> { + T::validate(*self) + } +} diff --git a/validator_derive/tests/range.rs b/validator_derive/tests/range.rs index 869510a..006d085 100644 --- a/validator_derive/tests/range.rs +++ b/validator_derive/tests/range.rs @@ -2,7 +2,7 @@ extern crate validator_derive; extern crate validator; -use validator::Validate; +use validator::{Validate, ValidationErrors}; #[test] fn can_validate_range_ok() { @@ -71,3 +71,22 @@ fn can_specify_message_for_range() { assert_eq!(errs["val"].len(), 1); assert_eq!(errs["val"][0].clone().message.unwrap(), "oops"); } + +#[test] +fn can_pass_reference_as_validate() { + // This tests that the blanket Validate implementation on + // `&T where T:Validate` works properly + + #[derive(Validate)] + struct TestStruct { + #[validate(range(min = 100))] + num_field: u32, + } + + fn validate(value: T) -> Result<(), ValidationErrors> { + value.validate() + } + + let val = TestStruct { num_field: 10 }; + validate(&val).unwrap_err(); +} -- cgit v1.2.3