【发布时间】:2018-08-19 07:48:35
【问题描述】:
我正在创建一个自定义 ConstraintValidator,以验证我的 JodaTime 对象的小时数是否在从弹簧表单输入的特定窗口内。
我的注释:
@Target({ElementType.METHOD, ElementType.FIELD})
@Documented
@Constraint(validatedBy = InputHoursValidator.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface InputHoursConstraint {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
我的验证者
public class InputHoursValidator implements ConstraintValidator<InputHoursConstraint, DateTime> {
private static final DateTimeFormatter HOURS_TIME_FORMAT = DateTimeFormat.forPattern("hh:mma");
private static final String EARLIEST_START_TIME = "5:00pm";
private static final String LATEST_END_TIME = "4:00am";
@Override
public void initialize(InputHoursConstraint constraintAnnotation) {
}
@Override
public boolean isValid(DateTime value, ConstraintValidatorContext context) {
return !value.isBefore(DateTime.parse(EARLIEST_START_TIME, HOURS_TIME_FORMAT))
&& !value.isAfter(DateTime.parse(LATEST_END_TIME, HOURS_TIME_FORMAT).plusDays(1));
}
}
还有我带有注释的魔力
public class HoursTrackingForm {
@NotNull(message = "Please enter a valid time in AM or PM")
@DateTimeFormat(pattern = "hh:mma")
@InputHoursConstraint(message = "Start time was before 5:00pm or after 4:00am")
private DateTime startTime;
@NotNull(message = "Please enter a valid time in AM or PM")
@DateTimeFormat(pattern = "hh:mma")
@InputHoursConstraint(message = "End time was before 5:00pm or after 4:00am")
private DateTime endTime;
//getters and setters
}
在我看来一切都很好,但是当我提交我的对象进行验证时,验证器中的 DateTime 始终为空。
【问题讨论】:
-
找不到代码有什么问题。它应该工作得很好。相反,验证本身的逻辑似乎是错误的,并且总是返回 false。
-
@S.K.每次我从我的春季表单提交请求时,逻辑除外,我在 DateTime 中返回 null。在添加此自定义约束之前不会发生这种情况。
标签: java spring-mvc