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

2

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?

Papeterie answered 21/5, 2014 at 22:27 Comment(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.Lachus
@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
@Lillianalillie 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.Papeterie
L
13

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

Lillianalillie answered 22/5, 2014 at 21:43 Comment(1)
Is there a reference somewhere where this is explicitly stated?Obala
T
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

Tracheitis answered 27/6, 2022 at 12:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.