使用Spring Boot或Hibernate Validator验证日期

时间:2017-06-05 19:34:54

标签: java spring validation spring-boot hibernate-validator

我使用Spring Boot构建了一个REST服务。我也在使用Hibernate Validator来验证数据。我有一个这样的REST端点:

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")以确保它们都是有效日期。我已尝试使用yyyy-MM-dd,但只要他们坚持2017-01-40,就不会给我验证错误。一个例子是2017-02-09,它只是解释为@DateTimeFormat。我猜@Pattern是格式化程序而不是验证程序。我还尝试使用Hibernate Validator的rexexp@Pattern(regexp="\\t(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d\\t"),如V000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.util.Date'. Check configuration for 'parameterDateAdjusted'。但这给了我错误

>> s = "http://domainname.com/products/prodName%20%20%20ProdNumber" >> Set r = New RegExp >> r.Global = True >> r.Pattern = "(%20)+" >> WScript.Echo s >> WScript.Echo r.Replace(s, "/") >> http://domainname.com/products/prodName%20%20%20ProdNumber http://domainname.com/products/prodName/ProdNumber >>

有任何建议我如何验证这些日期?

1 个答案:

答案 0 :(得分:2)

以下是为Date对象实现验证器的示例:

@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.
   }
}