0

Lets take this below use case.

I have bean with collection of some other bean as one of its properties:

public class MyBean {
    ...
    @Valid
    private NestedBean[] nestedBeans;
    ...
}

The nested bean has a custom class level constraint like this:

@SomeConstraint
public class NestedBean {
    ...
}

And we have a validator that validates this custom constraint:

public SomeConstraintValidator implements ConstraintValidator<SomeConstraint, NestedBean> {
    ...
    public boolean isValid(NestedBean bean, ConstraintValidatorContext context) {
        ...
    }
}

Is there a way to know the position of the current "bean" object that is getting validated, so that we can show error messages like:

"The third nested bean is invalid...."

Or is there any other way to achieve this?

The Hibernate's ConstraintValidationContext implementation hold property path with these details, but is not a public API.

  • You could try creating a validator for `NestedBean[]` directly and iterate over the array inside the `isValid` method. Then you would know the index. Something like `ConstraintValidator` – Michał Krzywański May 29 '20 at 14:32
  • Correct, I just wanted to check if we can get something from the framework itself. As I said, the ContraintValidatorContext actually has that information (as part of nodePath) but it is not a public API. – Aniruddha Deshpande May 30 '20 at 05:23

0 Answers0