There are two existing variants of this question:
String
field 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?
notNull() is a static method of the Validate class that is used to check whether the passed object is null or not. If the passed object is null , then the method raises an exception with a formatted message. If the passed object is not null , then the method returns the input as it is.
allNull() is a static method of the ObjectUtils class that is used to check if all the values in the array point to a null reference. The method returns false if any value in the array of values is not null . The method returns true if all the values in the passed array are null or the array is null or empty.
The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.
@Valid
references are only followed when they are not null, so something else must be causing your NPE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With