当我在数据库中插入新数据时,它不应小于要验证的当前日期。我该如何找到正确的RegEx?
@FutureOrPresent
@Pattern(message = "Invalid date", regexp = "?")
private Date dataInserted;
答案 0 :(得分:1)
您可以在PresentOrFuture.java中引入新的注释:
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PresentOrFutureValidator.class)
@Documented
public @interface PresentOrFuture {
String message() default "{PresentOrFuture.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
然后,您必须在PresentOrFutureValidator.java中定义验证器:
public class PresentOrFutureValidator
implements ConstraintValidator<PresentOrFuture, Date> {
public final void initialize(final PresentOrFuture annotation) {}
public final boolean isValid(final Date value,
final ConstraintValidatorContext context) {
// Only use the date for comparison
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date today = calendar.getTime();
// Your date must be after today or today (== not before today)
return !value.before(today) || value.after(today);
}
}
然后您必须设置:
@NotNull
@PresentOrFuture
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Temporal(TemporalType.DATE)
private Date startDate;