我的Spring Boot应用程序中有一个自定义注释,尽管有验证消息,它仍可正常工作......
这是我的自定义注释
@Documented
@Constraint(validatedBy = ReservationValidatorJSON.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidReservationJSON {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int day();
}
及其验证器
public class ReservationValidatorJSON implements ConstraintValidator<ValidReservationJSON, String> {
private final Logger logger = LoggerFactory.getLogger(ReservationValidatorJSON.class);
private int day;
@Override
public void initialize(ValidReservationJSON date) {
day = date.day();
}
@Override
public boolean isValid(String date, ConstraintValidatorContext ctx) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
DateTime dateToValidate = null;
try {
dateToValidate = new DateTime(sdf.parse(date));
DateTime now = new DateTime();
if (dateToValidate != null) {
return dateToValidate.isBefore(now.plusDays(day));
}
} catch (ParseException e) {
}
return false;
}
}
我以这种方式使用这个注释
@ValidReservationJSON(day=31)
private String fromDate;
然后我在我的消息属性中有了这个字段
ValidReservationJSON.fromDate = The beginning date cannot be after {day} days from now
当验证失败时,我会期待像
这样的消息The beginning date cannot be after 31 days from now
但我一直在
The beginning date cannot be after {day} days from now
答案 0 :(得分:0)
尝试此邮件而不是
ValidReservationJSON.fromDate = The beginning date cannot be after {1} days from now