Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to validate an object field only if it is not null?

There are two existing variants of this question:

  1. Validate only if the field is not Null : A solution to a conditionally handling a String field
  2. 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?

like image 504
Noremac Avatar asked May 21 '14 22:05

Noremac


People also ask

How do you validate NOT null?

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.

How do you check if all fields of an object are null?

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.

What is the difference between @valid and validated?

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.


1 Answers

@Valid references are only followed when they are not null, so something else must be causing your NPE.

like image 96
Gunnar Avatar answered Oct 06 '22 10:10

Gunnar