至少 24 小时后的休眠验证器注释
Annotation for hibernate validator for a date at least 24 hours in the future
我知道存在注解@Future。
如果我用这个注释来注释字段
@Future
private Date date;
日期必须在未来意味着在当前时刻之后。
现在我需要验证该日期至少比当前时刻晚 24 小时。
我怎样才能做到?
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());
}
}
此外,您可以在 ValidationMessages.properties
中添加默认 AfterTomorrow.message
消息
最后,注释您的字段:
@AfterTomorrow
private Date date;
我知道存在注解@Future。
如果我用这个注释来注释字段
@Future
private Date date;
日期必须在未来意味着在当前时刻之后。
现在我需要验证该日期至少比当前时刻晚 24 小时。
我怎样才能做到?
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());
}
}
此外,您可以在 ValidationMessages.properties
AfterTomorrow.message
消息
最后,注释您的字段:
@AfterTomorrow
private Date date;