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

我正在为作为@RestController方法中参数的bean编写测试。 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注释有关。在documentation中,声明了以下注释:

  

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

可以看到,不支持简单的String类型,但是我的POJO的日期字段是String。如上所述,我已经使用@DateTimeFormat进行了测试,并带有注释的参数,每次都互斥。显然,它没有解决问题。

问题本身-是否有任何注释或类似的解决方法可以在String类型变量中为特定的日期格式添加(使之称为)“验证器”?

libravilla 回答:Spring-验证bean中的String字段,它实际上是一个Date

此问题或之前询问和回答过的类似问题。以下是上一个问题的链接。请查看该答案是否对您有帮助。

Java String Date Validation Using Hibernate API

,

您可以为此情况创建自定义验证程序注释。例子

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:此代码来自我之前完成的项目。但是,是的,我阅读了链接,上面的代码也是如此

本文链接:https://www.f2er.com/3151025.html

大家都在问