File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change @@ -281,3 +281,67 @@ fn named_struct_custom_closure_vec_errors_is_err() {
281281 . to_string( )
282282 ) ;
283283}
284+
285+ #[ test]
286+ fn filed_custom_validation_use_self ( ) {
287+ fn food_validation ( kind : & str , food : & str ) -> Result < ( ) , serde_valid:: validation:: Error > {
288+ match kind {
289+ "cat" => {
290+ if food == "fish" {
291+ Ok ( ( ) )
292+ } else {
293+ Err ( serde_valid:: validation:: Error :: Custom (
294+ "Cat should eat fish." . to_string ( ) ,
295+ ) )
296+ }
297+ }
298+ "dog" => {
299+ if food == "meat" {
300+ Ok ( ( ) )
301+ } else {
302+ Err ( serde_valid:: validation:: Error :: Custom (
303+ "Dog should eat meat." . to_string ( ) ,
304+ ) )
305+ }
306+ }
307+ _ => Err ( serde_valid:: validation:: Error :: Custom (
308+ "Unknown pet type." . to_string ( ) ,
309+ ) ) ,
310+ }
311+ }
312+
313+ #[ derive( Validate ) ]
314+ struct Pet {
315+ #[ validate( enumerate = [ "cat" , "dog" ] ) ]
316+ kind : String ,
317+
318+ #[ validate( custom = |food| food_validation( & self . kind, food) ) ]
319+ food : String ,
320+ }
321+
322+ let cat = Pet {
323+ kind : "cat" . to_string ( ) ,
324+ food : "fish" . to_string ( ) ,
325+ } ;
326+ assert ! ( cat. validate( ) . is_ok( ) ) ;
327+
328+ let invalid = Pet {
329+ kind : "cat" . to_string ( ) ,
330+ food : "meat" . to_string ( ) ,
331+ } ;
332+
333+ assert_eq ! (
334+ invalid. validate( ) . unwrap_err( ) . to_string( ) ,
335+ json!( {
336+ "errors" : [ ] ,
337+ "properties" : {
338+ "food" : {
339+ "errors" : [
340+ "Cat should eat fish."
341+ ]
342+ }
343+ }
344+ } )
345+ . to_string( )
346+ ) ;
347+ }
You can’t perform that action at this time.
0 commit comments