Java 使用Spring引导或Hibernate验证程序验证日期
我已经使用SpringBoot构建了一个REST服务。我还使用Hibernate验证器来验证数据。我有这样一个REST端点:Java 使用Spring引导或Hibernate验证程序验证日期,java,spring,validation,spring-boot,hibernate-validator,Java,Spring,Validation,Spring Boot,Hibernate Validator,我已经使用SpringBoot构建了一个REST服务。我还使用Hibernate验证器来验证数据。我有这样一个REST端点: @PostMapping(value = "${apiVersion.v_1}" + "/parameter-dates") public ResponseEntity createParameterDate( @RequestBody ParameterDate parameterDate){ // Some code that use parameterDat
@PostMapping(value = "${apiVersion.v_1}" + "/parameter-dates")
public ResponseEntity createParameterDate( @RequestBody ParameterDate parameterDate){
// Some code that use parameterDate
}
public class ParameterDate {
@NotNull(message = "Parameter Date Unadjusted can not be blank or null")
private Date parameterDateUnadjusted;
@NotNull(message = "Parameter Date Adjusted can not be blank or null")
private Date parameterDateAdjusted;
private Date parameterDateAdded;
private Date parameterDateChanged;
}
ParameterDate
在如下类中定义:
@PostMapping(value = "${apiVersion.v_1}" + "/parameter-dates")
public ResponseEntity createParameterDate( @RequestBody ParameterDate parameterDate){
// Some code that use parameterDate
}
public class ParameterDate {
@NotNull(message = "Parameter Date Unadjusted can not be blank or null")
private Date parameterDateUnadjusted;
@NotNull(message = "Parameter Date Adjusted can not be blank or null")
private Date parameterDateAdjusted;
private Date parameterDateAdded;
private Date parameterDateChanged;
}
我想验证parameterDateUnadjusted
和parameterDateAdjusted
以确保它们都是有效日期。我试过使用@DateTimeFormat(pattern=“yyyy-MM-dd”)
,但只要它们坚持使用yyy-MM-dd
,它就不会给我一个验证错误,因为没有验证。一个例子是2017-01-40
,它只是解释为2017-02-09
。我想@DateTimeFormat
更像是一个格式化程序而不是一个验证器。我还尝试使用Hibernate验证程序的@Pattern
和rexexp
像@Pattern(regexp=“\\t(0[1-9]|[12][0-9]|[3[01])[-/.](0[1-9]| 1[012])[-/.](19[20)\\d\\t”)
。但这给了我一个错误
V00030:找不到约束“javax.validation.constraints.Pattern”验证类型“java.util.Date”的验证器。检查“parameterDateAdjusted”的配置
有没有关于如何验证这些日期的建议?以下是实现日期对象验证程序的示例:
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyDateValidator.class)
@Documented
public @interface ValidDate {
String message() default "some message here";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
public class MyDateValidator implements ConstraintValidator<ValidDate, Date> {
public void initialize(ValidDate constraint) {
}
public boolean isValid(Date value, ConstraintValidatorContext context) {
// validate the value here.
}
}
@Target({ElementType.FIELD})
@保留(RetentionPolicy.RUNTIME)
@约束(validatedBy=MyDateValidator.class)
@记录
public@interface ValidDate{
String message()默认为“此处有消息”;
类[]组()默认值{};
ClassI认为REST服务验证是应该使用的。当您进入休眠状态时,数据应该得到验证。@duffymo谢谢。我将如何实现它?请看一下将lenient设置为false:@du@hooknc在使用注释@DateTimeFormat
时,如何将lenient设置为false?好吧,这是一个好问题。我认为这是一个意外ally在我准备好之前点击了“添加评论”,无法返回并按我想要的方式编辑我的评论。根据我的快速研究,似乎无法在hibernate的@DateTimeFormat上设置宽松值。但是,您可以非常简单地实现自己的验证程序: