29

I have a problem with validation of nested models, look:

class A{
   @NotNull
   Integer i;
   B b;
}
class B{
   @NotNull
   Integer j;
}

In spring controller:
@Valid @RequestBody...

It properly validate i, but not validate j. How to force Spring to validate arbitraly deep ?

And second thing:
Is it possible to do following validation: Object of class 'A' is proper only and only if exactly one of i an j is null.

class A{
   Integer i;
   Integer j;
}

1 Answer 1

68

Object graph validation is supported and you have to annotate B b with @Valid like below.

class A{
  @NotNull
  Integer i;
  @Valid
  B b;
}

Please refer https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=5.3#section-object-graph-validation for more details.

For second part of you question, you can create a custom Validator class. You would also need a custom annotation for that Validator. You can check the details at documentation page here. A sample for custom Validator is here.

Sign up to request clarification or add additional context in comments.

3 Comments

What if B is a collection that contains the items to be validated? Will it also work?
@TheRealChx101 it's an old answer, but yes, it will work.
I can confirm that it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.