Search code examples
jaxbbean-validationmoxyjaxb2

Validation is skipped when constraints are only in parent class


I am using MOXy as JAXB provider along with Bean Validation.

I'm trying to validate a class where only parent fields are annotated with constraints.

I can see that MOXy is skipping validation for this class, probably it is not looking into the parent class.

Can you advise on how to overcome this?


Solution

  • I found a quick workaround. It is about creating dummy constraints which will always pass. Then you can put it on any class. and MOXy will turn on validation.

    Dummy constraints:

    @Target( {ElementType.CONSTRUCTOR})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = PutItWhenYouDoNotHaveConstraintsButParentHas.Validator.class)
    @Documented
    public @interface  PutItWhenYouDoNotHaveConstraintsButParentHas {
    
        String message() default "{com.mycompany.constraints.checkcase}";
        Class<? extends Payload>[] payload() default {};
        Class<?>[] groups() default {};
        public static class Validator implements ConstraintValidator<PutItWhenYouDoNotHaveConstraintsButParentHas, Object>{
    
            @Override
            public void initialize(PutItWhenYouDoNotHaveConstraintsButParentHas constraintAnnotation) {
    
            }
    
            @Override
            public boolean isValid(Object value, ConstraintValidatorContext context) {
                return true;
            }
        }
    }
    

    Example usage:

    public class IdoNotHaveConstraints extends ButMyParentHas{
    
        @PutItWhenYouDoNotHaveConstraintsButParentHas
        public IdoNotHaveConstraints (){
    
        }
    }