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

爱⌒轻易说出口 提交于 2019-12-22 08:44:01

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/29637732/annotation-for-hibernate-validator-for-a-date-at-least-24-hours-in-the-future

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!