Generic field validation


#1

I want to apply a constraint on all string property of an object, but with the programmatic api as I don’t want to annotate all property.

class Foo  {

   String value1;
   Integer value2;
   @Valid
   Bar value3;
}

class Bar {
    String value4;
    Boolean value5;
}

Here if I validate the object Foo, I would like to have the properties value1 and value4 to be validated with my constraint. I tried the following but I cannot specify wild card for fields.

ConstraintMapping constraintMapping = hibernateValidatorConfiguration.createConstraintMapping();
constraintMapping
                    .type(Object.class)
                    .property("*", ElementType.FIELD)
                    .type(String.class)
                    .constraint( new GenericConstraintDef<>(MyConstraint.class));
hibernateValidatorConfiguration.addMapping(constraintMapping);

I think that I am looking to some property selector feature that I dont find.


#2

We don’t have something built-in in HV.

You can simply use the standard Java reflection API to get the fields of your class and iterate on them.