Noremac
Noremac

Reputation: 3547

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?

Upvotes: 8

Views: 18450

Answers (2)

Tr4d
Tr4d

Reputation: 25

@Valid references does not seem to be followed only if they are not null. If I provide a custom validation annotation without checking for null, It throws a NPE. You need to check for null value yourself inside the validator.

For example:

    public class EmailListValidator implements ConstraintValidator<EmailListConstraint, String> {

    @Override
    public void initialize(final EmailListConstraint emailListConstraint) {
    }

    @Override
    public boolean isValid(final String emailList, final ConstraintValidatorContext cxt) {
        if (emailList != null) {
           // Validation logic here      
        }
        return true;
    }
}

Here is a link from baeldung website on how to implement a custom validation annotation : https://www.baeldung.com/spring-mvc-custom-validator

Upvotes: 1

Gunnar
Gunnar

Reputation: 18980

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

Upvotes: 13

Related Questions