Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 505
gstackoverflow Avatar asked Apr 16 '15 22:04

gstackoverflow


People also ask

How do you check date is future or not?

To check if a date is in the future:Use the Date() constructor to get the current date. Optionally set the time of the current date to the last millisecond. Check if the date is greater than the current date.

How do you validate a date range?

Steps to Create Date Validation with Date Range From here in the data validation dialog box, select “Date” from the “Allow” drop-down. After that, select between from the “Data” drop-down. Next, you need to enter two dates in the “Start Date” and “End Date” input boxes. In the end, click OK.


2 Answers

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)

like image 198
Neil McGuigan Avatar answered Oct 06 '22 23:10

Neil McGuigan


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);
}
like image 33
myrillia Avatar answered Oct 07 '22 01:10

myrillia