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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With