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

落爺英雄遲暮 提交于 2019-12-05 12:19:55

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