File tree Expand file tree Collapse file tree 2 files changed +90
-0
lines changed Expand file tree Collapse file tree 2 files changed +90
-0
lines changed Original file line number Diff line number Diff line change 256256//! assert!(s.validate().is_ok());
257257//! ```
258258//!
259+ //! You can use **closure**, so you can access other fields of the struct by using the `self` keyword.
260+ //!
261+ //! ```rust
262+ //! use serde_valid::Validate;
263+ //!
264+ //! #[derive(Validate)]
265+ //! struct Data {
266+ //! val1: i32,
267+ //! #[validate(custom = |val2: &i32| {
268+ //! if self.val1 < *val2 {
269+ //! Ok(())
270+ //! } else {
271+ //! Err(serde_valid::validation::Error::Custom("val2 must be greater than val1".to_owned()))
272+ //! }
273+ //! })]
274+ //! val2: i32,
275+ //! }
276+ //!
277+ //! let s = Data { val1: 2, val2: 1 };
278+ //!
279+ //! assert_eq!(
280+ //! s.validate().unwrap_err().to_string(),
281+ //! serde_json::json!({
282+ //! "errors": [],
283+ //! "properties": {
284+ //! "val2": {
285+ //! "errors": ["val2 must be greater than val1"]
286+ //! }
287+ //! }
288+ //! })
289+ //! .to_string()
290+ //! );
291+ //! ```
292+ //!
259293//! Custom validation is suitable for handling convenience validations not defined in JSON Schema.
260294//! `serde_valid::utils::*` provides convenience functions for specific types.
261295//!
Original file line number Diff line number Diff line change @@ -281,3 +281,59 @@ fn named_struct_custom_closure_vec_errors_is_err() {
281281 . to_string( )
282282 ) ;
283283}
284+
285+ #[ test]
286+ fn filed_custom_validation_using_self ( ) {
287+ fn food_validation ( kind : & str , food : & str ) -> Result < ( ) , serde_valid:: validation:: Error > {
288+ match kind {
289+ "Cat" => {
290+ if food == "CatFood" {
291+ Ok ( ( ) )
292+ } else {
293+ Err ( serde_valid:: validation:: Error :: Custom (
294+ "Cat should eat CatFood." . to_string ( ) ,
295+ ) )
296+ }
297+ }
298+ "Dog" => {
299+ if food == "DogFood" {
300+ Ok ( ( ) )
301+ } else {
302+ Err ( serde_valid:: validation:: Error :: Custom (
303+ "Dog should eat DogFood." . to_string ( ) ,
304+ ) )
305+ }
306+ }
307+ _ => Ok ( ( ) ) ,
308+ }
309+ }
310+
311+ #[ derive( Validate ) ]
312+ struct Pet {
313+ #[ validate( enumerate = [ "Cat" , "Dog" ] ) ]
314+ kind : String ,
315+
316+ #[ validate( custom = |food| food_validation( & self . kind, food) ) ]
317+ food : String ,
318+ }
319+
320+ let invalid = Pet {
321+ kind : "Cat" . to_string ( ) ,
322+ food : "DogFood" . to_string ( ) ,
323+ } ;
324+
325+ assert_eq ! (
326+ invalid. validate( ) . unwrap_err( ) . to_string( ) ,
327+ json!( {
328+ "errors" : [ ] ,
329+ "properties" : {
330+ "food" : {
331+ "errors" : [
332+ "Cat should eat CatFood."
333+ ]
334+ }
335+ }
336+ } )
337+ . to_string( )
338+ ) ;
339+ }
You can’t perform that action at this time.
0 commit comments