Reputation: 26914
I'm doing analyses on Java validation.
I need to build a module that validates an object [graph] field-by-field, using annotation and supporting custom domain-driven annotations. The most important aspect is that an invalid object must not be rejected (e.g. by underlying persistence layer) but instead marked as invalid.
For example, pick a class with a number of attributes. If any is invalid (e.g. missing or bad valued) I want to know which one is and mark it in another place as invalid. It is important that I get the name of all the fields that didn't pass validation, whether it's a primitive field or a child entity with a validation problem.
I have taken a look at javax.validation
but I couldn't figure out the role of ConstraintViolation
: it is returned by the validator when a validation error is found, but AFAIK doesn't show the field name to collect.
The question is: do you have any example of using any implementation of javax.validation that display the list of the field names that are found to be invalid for each validated bean?
Also, can I introduce custom attributes instead of adding a ValidatedBy
attribute for each recurring attribute to be validated with custom logic?
Upvotes: 3
Views: 1839
Reputation: 51473
If you want the name of the element that caused the ConstraintViolation you must use
Path path = ConstraintViolation.getPropertyPath();
// a path is an iterable of Path.Node objects
// the last node element in the path is the element that caused the violation
// You can get it's name via
Path.Node node = ...;
node.getName();
Take a look at the JSR-303 spec chapter 4.2 for details on the Path.
Upvotes: 4