[2.0.3-java] validate() with nested objects

230 views
Skip to first unread message

Joel Söderström

unread,
Oct 4, 2012, 1:53:32 PM10/4/12
to play-fr...@googlegroups.com
Hi,

I am utilizing validate() methods for custom validation:


public class Foo {

// Fields...
public Map<String, List<ValidationError>> validate() {
// Validation logic here...
                // return map so that I can create field errors
return map;
}

}

This is cool when I just validate Foo directly. However, when I nest Foo in another object that I validate I get into trouble:

public class Bar {
@Valid
public Foo foo;

}

What happens is that Foo's validate() method is not invoked when I validate Bar. 
I have worked around this by calling Foo's validate from Bar's validate. But it gets a bit messy since I then need to alter field paths so that it points to the nested object (I create field errors, not global errors). 

Is this by design or a bug? 
Is there any other, better way to perform custom validation?    

Knowing that Play takes care of invoking any validate() methods in nested objects when it's annotated with @Valid would be sooo much nicer. Plus if Play could take care of field paths when a field error is posted in a nested objects validate() method.

Joel

James Roper

unread,
Oct 4, 2012, 7:16:52 PM10/4/12
to play-fr...@googlegroups.com
This is by design, if you read the docs carefully it says:

You can also define an ad-hoc validation by adding a validate method to your top object:

The validate method is there in part to allow for 100% flexible validation.  In order to give full power to users, I think it should be up to validate to decide if child objects should have their validate methods called, for example you may only want the child objects validate method to be called if a certain condition holds on another field.

It shouldn't be hard to namespace keys in the returned Map, a simple helper utility that accepts the target map, the field name and the source map could easily be written that you can reuse everywhere in your app.

Joel Söderström

unread,
Oct 5, 2012, 9:53:16 AM10/5/12
to play-fr...@googlegroups.com
OK, thanks for the explanation, much appreciated!

Will look into creating a util for this. I remember Spring had the concept of push/pop nested path when traversing nested object during validation so that they were namespaced. This is probably something similar. 

Joel
Reply all
Reply to author
Forward
0 new messages