Java Bean Validation (JSR303) constraints involving relationship between several bean properties

前端 未结 5 1578
粉色の甜心
粉色の甜心 2020-12-05 00:43

Say I have the following simple java bean:

class MyBean {
   private Date startDate;
   private Date endDate;
   //setter, getters etc...
}

相关标签:
5条回答
  • 2020-12-05 01:28

    Since there is no way to access the bean in a JSR 303 validator, this is not possible.

    A workaround would be to supply your own ConstraintValidatorContext and extend it with a reference to the bean you're currently validating. But I'm not sure whether you can modify/override the respective factory.

    0 讨论(0)
  • 2020-12-05 01:31

    The answer is a class level validator. You can define custom constraints which you can place on entity class. At validation time you get passed the whole instance into the isValid() method. You can then compare your two dates against each other. See also the Hibernate Validator documentation.

    0 讨论(0)
  • 2020-12-05 01:42

    @AssertMethodAsTrue - A reusable constraint annotation that spans multiple properties.

    0 讨论(0)
  • 2020-12-05 01:44

    I can think of a few things to try.

    You could create a Constraint with a target of the type itself with an appropriate validator:

    @ValidateDateRange(start="startDate", end="endDate")
    public class MyBean {
    

    You could encapsulate a date range in a type and validate that:

    public class DateRange {    
      private long start;
      private long end;
    
      public void setStart(Date start) {
        this.start = start.getTime();
      }
    
      // etc.
    

    You could add a simple property that performs the check:

    public class MyBean {
      private Date startDate;
      private Date endDate;
    
      @AssertTrue public boolean isValidRange() {
        // TODO: null checks
        return endDate.compareTo(startDate) >= 0;
      }
    
    0 讨论(0)
  • 2020-12-05 01:49

    If you're using Hibernate Validator in version 4.1 or later you can use the @ScriptAssert constraint together with a scripting or expression language to express this kind of constraint. Using JavaScript your example would look like this:

     @ScriptAssert(lang = "javascript", script = "_this.startDate.before(_this.endDate)")
     public class CalendarEvent {
    
          private Date startDate;
    
          private Date endDate;
    
          //...
     } 
    

    You can get an even more compact syntax by creating a custom constraint for the script language of your choice:

    @JexlAssert("_.startDate < _.endDate")
    public class CalendarEvent {
    
        private Date startDate;
    
        private Date endDate;
    
        //...
    }
    
    0 讨论(0)
提交回复
热议问题