-1

I need to check if an End Date is greater than start Date in Back side. I've read about validators but I don't know how to use them and I am wondering if there's another alternative(add constraint as Annotation Maybe ..).

Any recommendation or suggestion would be great!

C.Gh
  • 107
  • 2
  • 6
  • where store start and end time? Is it store on one DTO? – Maxim Kasyanov Jul 12 '18 at 09:52
  • Yes ,they belong to the same entity – C.Gh Jul 12 '18 at 10:41
  • Why you don't implement it by yourself? You could create Interface Validator with validate(T t) method. After validation return boolean or List or throw new excpetion – Maxim Kasyanov Jul 12 '18 at 10:42
  • it seems to be the best solution and I am working on it now, if you have any good validators' examples ,it would be so helpful – C.Gh Jul 12 '18 at 10:49
  • Please refer to this [answer](https://stackoverflow.com/questions/1972933/cross-field-validation-with-hibernate-validator-jsr-303/2155576#2155576). Hope it helps. – rafisameen Sep 01 '20 at 21:10

2 Answers2

0

There is no spring annotation for such validation. You can do it on your own like plain oldshool over the setter:

public class MyEntity... {
    ...
    private LocalDate shouldBeAfterNow;

    public void setShouldBeAfterNow(LocalDate date) {
         if(date.isAfter(LocalDate.now())) {
           shouldBeAfterNow = date;
         } else {
           throw new SomeException(); // or
         }
    }
    ...
}

But please consider if you really need such validation in the entity. Maybe there is a better place for this... maybe the service or mapper class.

0bmis
  • 46
  • 1
  • 8
-1

In your method you can use an Assertion: Assert.isTrue(endDate.isAfter(startDate),"Custom message");

The custom message is optional.

Bart
  • 267
  • 1
  • 10
  • hello, Which method do you mean ? I only have attributes and want to check on them – C.Gh Jul 12 '18 at 08:14
  • I'm assuming you create an object with the dates as parameters? Before creating the object ( or in the constructor ) you can add this to check the dates. If you could provide some example code I can have a better picture of your situation :) – Bart Jul 12 '18 at 08:17