8

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?

3
  • I'd say that this a complex enough use case to require you to use a custom validator. Write your logic inside a validator, give it an annotation and do what you need to do.
    – JamesENL
    May 22, 2014 at 2:15
  • 1
    @Valid references are only followed when they are not null. Can you show your classes and describe where exactly the NPE is raised (stacktrace)?
    – Gunnar
    May 22, 2014 at 6:40
  • @Gunnar you are indeed correct. I did a simple test case and it worked as you said. It is now working in the more complex use case as well. Go ahead and write an answer so I can mark this mystery as solved.
    – Noremac
    May 22, 2014 at 15:00

2 Answers 2

13

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

1
  • 3
    Is there a reference somewhere where this is explicitly stated? Nov 18, 2019 at 11:40
1

@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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.