Search code examples
javahibernatespring-boothibernate-validator

Hibernate Validator Custom Constraint depends on base class


Can I create a custom constraint with Hibernate Validator (w/i Spring boot), where the validation depends on sub class? Example:

public class Engine {
   @NotEmpty
   private String name;
   @NotNull
   private int power;
   @NotNull // HERE I ONLY NEED VALIDATE IF THIS CLASS ARE ONE PROP FROM Car Class
   private int color;

   ... getter and setter
}

Here I have 2 classes,

public class Car {
   @NotEmpty
   private String name;
   @Valid
   private Engine engine;
   ... getter and setter
}

public class Bike {
   @NotEmpty
   private String name;
   @Valid
   private Engine engine; // HERE I DONT NEED TO VALIDATE THE COLOR
   ... getter and setter
}

Solution

  • You should be able to do what you want using @ConvertGroup:

    The group interfaces:

    public interface BasicEngineChecks {
    }
    
    public interface ExtendedEngineChecks {
    }
    

    Updated example:

    @GroupSequence({ BasicEngineChecks.class, ExtendedEngineChecks.class })
    public class Engine {
       @NotEmpty(groups = BasicEngineChecks.class)
       private String name;
    
       @NotNull(groups = BasicEngineChecks.class)
       private int power;
    
       @NotNull(groups = ExtendedEngineChecks.class)
       private int color;
    
       // ...
    }
    

    There is nothing special about car. Cascaded validation will pass through the default group which gets translated to all constrains which are part of BasicEngineChecks as well as ExtendedEngineChecks

    public class Car {
       @NotEmpty
       private String name;
    
       @Valid
       private Engine engine;
    
       // ...
    }
    

    For Bike we do a explicit conversion only evaluating BasicEngineChecks:

    public class Bike {
       @NotEmpty
       private String name;
    
       @Valid
       @ConvertGroup(from = Default.class, to = BasicEngineChecks.class)
       private Engine engine; 
    
       // ...
    }