There are two existing variants of this question:
- Validate only if the field is not Null : A solution to a conditionally handling a
String
field - Hibernate validation - only validate if object is not null : The only answer demonstrates the behavior and hints at how you could handle it when triggering the validation manually.
My question adds the qualifier of how can I do this when using @Valid on an object which may be null.
The use case here is that we have two fields where one or the other need to be not null (Custom validator on the class that contains the fields). When one is not null, I need it to be valid. Do I then need to fully and manually validate that object within my custom validator, adding more responsibility to it than it was intended for?
Using only annotations in this case causes a NullPointerException to be thrown, which breaks it out of validation before it could be handled. Is there not currently a way to do this?
@Valid
references are only followed when they are not null. Can you show your classes and describe where exactly the NPE is raised (stacktrace)? – Lillianalillie