Spring-validate bean中的String字段,它实际上是一个Date



我正在为一个bean编写测试,该bean是@RestController方法中的一个参数。Bean POJO:

public class AddTownRequestBean
{
@NotEmpty(message = "INVALID_REQUEST")
@Length(min = 1, max = 30, message = "PARAMETER_OUT_OF_BOUNDS")
private String name;
@NotEmpty(message = "INVALID_REQUEST")
@Length(min = 3, max = 4, message = "PARAMETER_OUT_OF_BOUNDS")
private String typeCreated;
@DateTimeFormat(pattern = "yyyy-MM-dd") //style = "S-", iso = DateTimeFormat.ISO.DATE,
private String foundationDate;
getters and setters...
}

我的问题与@DateTimeFormat注释有关。文件中指出,该注释:

可以应用于java.util.Date,java.util.Calendar,Long(表示毫秒时间戳(以及JSR-310 java.time和Joda time值类型。

可以看到,不支持简单的String类型,但我的POJO的日期字段是String。我已经使用如上所述的@DateTimeFormat进行了测试,也使用了注释参数,每次都相互排除。显然没有成功。

因此,问题本身——是否有任何注释或类似的解决方法可以在String类型的变量中为特定日期格式添加(我们称之为("验证器",该变量本应是日期?

这个问题或以前问过并回答过的类似问题。以下是上一个问题的链接。请看这个答案是否对你有帮助。

使用Hibernate API 的Java字符串日期验证

您可以为这种情况创建自定义验证器注释。示例

DateTimeValid.class

@Constraint(validatedBy = DateTimeValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DateTimeValid{
public String message() default "Invalid datetime!";
public String fomart() default "MM/dd/yyyy";
public Class<?>[] groups() default {};
public Class<? extends Payload>[] payload() default {};
}

DateTimeValidator.class

public class DateTimeValidator implements ConstraintValidator<DateTimeValid, String> {
private String dateFormat;
@Override
public void initialize(DateTimeValid constraintAnnotation) {
dateFormat = constraintAnnotation.fomart();
}
@Override
public boolean isValid(String strDate, ConstraintValidatorContext context) {
try {
DateFormat sdf = new SimpleDateFormat(this.dateFormat);
sdf.setLenient(false);
sdf.parse(strDate);
} catch (Exception e) {
return false;
}
return true;
}
}

用法

@DateTimeValid(fomart="...", message="...")
private String foundationDate;

编辑:@Ramu:这是我以前做过的项目中的代码。但是,是的,我读了链接,上面的代码也是一样的想法

最新更新