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

前端 未结 5 1580
粉色の甜心
粉色の甜心 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: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;
      }
    

提交回复
热议问题