Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotation for hibernate validator for a date at least 24 hours in the future

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?

like image 521
gstackoverflow Avatar asked Dec 15 '22 15:12

gstackoverflow


1 Answers

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;
like image 62
beerbajay Avatar answered Dec 17 '22 06:12

beerbajay