Maybe I'm doing something incorrectly, but I'd like to kindly ask you if there is a better way of doing deeply nested cross-validation, as I find Bean Validation API hard to use i such cases.
Hope that it's a good place to search for an answer.
I've created
https://github.com/perceptron8/bval-example/ so you can see what it's all about.
Please compare
https://github.com/perceptron8/bval-example/blob/master/src/main/java/bval/MyValidator.javaand
https://github.com/perceptron8/bval-example/blob/master/src/main/java/bval/MyConstraintValidator.java.
It's impossible (or I don't know that it is possible) to create nested context and reuse it, mainly because one can't specify path components without giving error message first.
What I mean is that you can't write something like
Code:
ConstraintValidatorContext nestedContext = context
.startNestedContextWithoutMessage()
.addPropertyNode(...)
...
.stopNestedContextAndPointHere()
.inIterable().atIndex(...); // this could point to x.y[yi].z[zi]
and then maybe
Code:
nestedContext
.buildConstraintViolationWithTemplate(...)
.addPropertyNode(...)
.addConstraintViolation()
.disableDefaultConstraintViolation(); // this could resolve to x.y[yi].z[zi].val
or just
Code:
nestedContext
.addConstraintViolation(); // same as above, but with default message
Instead, you are forced to recreate whole path every time you want to add constraint violation. That's painful.
As you can see, there is no way to implement Z Validation without access to X fields, so one must create class-level constaint for X. Someone could argue that it's just a matter of adding back-refs from Z to Y and from Y to X and annotating Z,
but a) that's impossible if you don't own the model, b) Z's parent may be context dependent (imagine that both X->Y1->Z and X->Y2->Z are possible, where Y1 and Y2 fields are distinct classes). I'm stuck with both a) and b).
Don't get me wrong. I know that BV2 has much broader scope. At the same time I must confess that most of the time I find Spring's Errors stack-like behavior much more pleasant to use - despite not being type-safe.
Is there something that I missed?
Best regards
MichaĆ