4

I know that exist annotation @Future.

If I annotate field with this annotation

@Future
private Date date;

date must be in future means after current moment.

Now I need to validate that date was at least 24 hours after current moment.
How can I make it?

beerbajay
  • 19,652
  • 6
  • 58
  • 75
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

1 Answers1

12

AfterTomorrow.java:

@Target({ FIELD, METHOD, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = AfterTomorrowValidator.class)
@Documented
public @interface AfterTomorrow {
    String message() default "{AfterTomorrow.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

AfterTomorrowValidator.java:

public class AfterTomorrowValidator 
             implements ConstraintValidator<AfterTomorrow, Date> {
    public final void initialize(final AfterTomorrow annotation) {}

    public final boolean isValid(final Date value,
                                 final ConstraintValidatorContext context) {
        Calendar c = Calendar.getInstance(); 
        c.setTime(value); 
        c.add(Calendar.DATE, 1);
        return value.after(c.getTime());
    }
}

Additionally, you can add the default AfterTomorrow.message message in ValidationMessages.properties

Finally, annotate your field:

@AfterTomorrow
private Date date;
beerbajay
  • 19,652
  • 6
  • 58
  • 75
  • Can you advise where can I determine file name where I store validation messages – gstackoverflow Apr 14 '15 at 21:45
  • Assuming you're using hibernate validator, put them in `src/main/resources/ValidationMessages.properties`. Theoretically you can put the messages in another file, but I've never gotten this to work. – beerbajay Apr 14 '15 at 21:48