Based on the number of times the question is displayed, I conclude that a lot of people still end up here looking for a validator for a date range.
Suppose we have a DTO containing another DTO (or class with @Embeddable
annotation) with two fields with LocalDate
(or other date representation, it's only example).
class MyDto {
@ValidDateRange // <-- target annotation
private DateRange dateRange;
// getters, setters, etc.
}
class DateRange {
private LocalDate startOfRange;
private LocalDate endOfRange;
// getters, setters, etc.
}
Now, we can declare our own @ValidDateRange
annotation:
@Documented
@Constraint(validatedBy = DateRangeValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface ValidDateRange {
String message() default "Start date must be before end date";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
Writing the validator itself also comes down to a few lines of code:
class DateRangeValidator implements ConstraintValidator<ValidDateRange, DateRange> {
@Override
public boolean isValid(DateRange value, ConstraintValidatorContext context) {
return value.getStartOfRange().isBefore(value.getEndOfRange());
}
}