10

I have following bean:

class CampaignBeanDto {

    @Future
    Date startDate;

    Date endDate;

    ...
}

Obviously I that endDate should be after startDate. I want to validate it.

I know that I can manually realize annotation for @FutureAfterDate, validator for this and initialize threshold date manually but I want to use @Validated spring mvc annotation.

How can I achieve it?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

2 Answers2

7

You're gonna have to bear down and write yourself a Validator.

This should get you started:

Cross field validation with Hibernate Validator (JSR 303)

Community
  • 1
  • 1
Neil McGuigan
  • 46,580
  • 12
  • 123
  • 152
6

You should not use Annotations for cross field validation, write a validating function instead. Explained in this Answer to the Question, Cross field validation with Hibernate Validator (JSR 303).

For example write a validator function like this:

public class IncomingData {

  @FutureOrPresent
  private Instant startTime;

  @Future
  private Instant endTime;

  public Boolean validate() {
      return startTime.isBefore(endTime);
  }
}

Then simply call the validator function when first receiving the data:

if (Boolean.FALSE.equals(incomingData.validate())) {
  response = ResponseEntity.status(422).body(UNPROCESSABLE);
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
myrillia
  • 61
  • 1
  • 2