gstackoverflow
gstackoverflow

Reputation: 36984

How to validate that date in future in reference to another date?

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?

Upvotes: 10

Views: 20762

Answers (2)

myrillia
myrillia

Reputation: 59

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);
}

Upvotes: 5

Neil McGuigan
Neil McGuigan

Reputation: 48256

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)

Upvotes: 8

Related Questions