Reputation: 3547
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?
Upvotes: 8
Views: 18450
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
Reputation: 18980
@Valid
references are only followed when they are not null, so something else must be causing your NPE.
Upvotes: 13