Supose we have an object that extends another and I want to create a custom validation for both, example: Period and PeriodAmount objects. Where Period is:
public class Period {
private LocalDate startDate;
private LocalDate endDate;
And PeriodAmount is:
public class PeriodAmount extends Period {
private BigDecimal amount;
I have a custom validator for Period, like this:
public class PeriodValidator implements ConstraintValidator<ValidPeriod, Period> {
@Override
public boolean isValid(Period period, ConstraintValidatorContext context) {
LocalDate startDate = period.getStartDate();
LocalDate endDate = period.getEndDate();
if (startDate == null) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("{invalid.start.date.null}").addConstraintViolation();
return false;
}
if (endDate != null && startDate.isAfter(endDate)) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("{invalid.end.date.value}").addConstraintViolation();
return false;
}
return true;
}
}
This is working perfect for Period. But now I want a custom validator for PeriodAmount and I want to reuse the code that I already have for Period validation. How can I do this in order to call only one validation and have everything validated:
@ValidPeriodAmount
private PeriodAmount periodAmount;