javavalidationcustomvalidatorjavax.validation

Javax nested multiple validations


I have two classes. One is class A, the other class B. Class A has a string field which has a custom validation for checking base 64 encoding. Class B has a list of class A instances. I need to add a custom validator for this list which checks total size in bytes. When I add the custom validator on the list of A instances in B, it works but the validator for my Class A string field won't trigger. If I remove custom validator @ValidTotalSize, then @ValidEncoding works.

Class A {
   @ValidEncoding
   private string content
}

Class B {
   @ValidTotalSize
   private List<A> contentList
}

My JUnit - in this I am trying to test for encoding of content inside A. I purposefully pass incorrect encoding so that I have a failed constraint and I want to assert that. But after adding the @ValidTotalSize on contentList inside B, the @ValidEncoding won't even trigger. How can I ensure both validations are triggered?

@Test
public void testContentEncoding() {
   //create stub with incorrect encoded content
   final Set<ConstraintViolation<B>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(stub);
   Assert.assertTrue(!violations.isEmpty());
}

How can I make both work? One to validate the inner content and then one to validate the list.


Solution

  • I figured what I was missing. I needed to add the @Valid annotation too on to the contentList to trigger validation of each element in the list.

    @Valid
    @ValidTotalSize
    private List<A> contentList