1

I have a POJO annotated with JSR-303 annotations. Some of its attributes are other POJOs. I would like the inner POJOs to be @Valid, only if they are not null. But if they're null it's OK. Unfortunately I'm not succeding in doing this, so Java returns me the error for the inner POJOs attribute if they're null.

@AllArgsConstructor @NoArgsConstructor @Data
class OuterPojo{
    @NotBlank private String attributeA;
    @Valid    private InnerPojo attributeB;
}

@AllArgsConstructor @NoArgsConstructor @Data
class InnerPojo{
    @NotBlank private String attributeC;
    @NotNull  private Double attributeD;
}

I want an outerPojo to be valid if:

  1. attributeA is not-null and attributeB is null;
  2. attributeB is not-null and attributeB is not-null and valid.

So I would like the constraints on the attributes of inner pojo to be respected only if inner pojo is not null.

I've tried adding @Nullable to attributeB with no effect. How can I solve this?

Alessandro Argentieri
  • 2,901
  • 3
  • 32
  • 62
  • How exactly are you validating these fields? I just quickly added this setup in spring `ConfigurationProperties` and it worked exactly as you intended. 1. Didn't specify B at all, thus `null` value, which passed, no error detected. 2. Specified only C and leaving D as `null` and it failed, due to D being null. 3. Specified both C and D with valid values and it passed. So everything worked. – randomUser56789 Jan 03 '18 at 14:33
  • I use it to validate an xml input. I've just figured out that it's because I generate . Erasing these it works perfectly as you've just said. Thanks! – Alessandro Argentieri Jan 03 '18 at 14:46

1 Answers1

1

Just adding @Valid should mean valid if not null. Section 3.5.1 of the JSR 303: Bean Validation specification says "Null references are ignored" when validating the object graph.

I verified this using Hibernate Validator 6.0.2.Final and this simple test class.

public class Main {
    public static void main(String[] args) {
        OuterPojo outer = new OuterPojo("some value", null);
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator v = factory.getValidator();
        Set<ConstraintViolation<OuterPojo>> errors = v.validate(outer);
        for (ConstraintViolation<OuterPojo> violation : errors) {
            System.out.println(violation.getMessage());
        }
    }
}
Corey
  • 664
  • 9
  • 18