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

前端 未结 5 1588
粉色の甜心
粉色の甜心 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条回答
  •  猫巷女王i
    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;
    
        //...
    }
    

提交回复
热议问题