【问题标题】:Validating Date - Bean validation annotation - With a specific format验证日期 - Bean 验证注释 - 具有特定格式
【发布时间】:2013-07-06 13:23:20
【问题描述】:

我想验证 YYYY-MM-DD_hh:mm:ss 格式的日期

@Past //validates for a date that is present or past. But what are the formats it accepts

如果那不可能,我想使用@Pattern。但是在@Pattern 中使用上述格式的regex 是什么?

【问题讨论】:

  • 如果你碰巧使用 Spring,你可以使用@DateTimeFormat

标签: java date design-patterns format bean-validation


【解决方案1】:

@Past 仅支持 DateCalendar,但不支持字符串,因此没有日期格式的概念。

您可以创建一个自定义约束,例如 @DateFormat,以确保给定的字符串符合给定的日期格式,约束实现如下:

public class DateFormatValidatorForString
                           implements ConstraintValidator<DateFormat, String> {

    private String format;

    public void initialize(DateFormat constraintAnnotation) {
        format = constraintAnnotation.value();
    }

    public boolean isValid(
        String date,
        ConstraintValidatorContext constraintValidatorContext) {

        if ( date == null ) {
            return true;
        }

        DateFormat dateFormat = new SimpleDateFormat( format );
        dateFormat.setLenient( false );
        try {
            dateFormat.parse(date);
            return true;
        } 
        catch (ParseException e) {
            return false;
        }
    }
}

请注意,SimpleDateFormat 实例不能存储在验证器类的实例变量中,因为它不是线程安全的。或者,您可以使用 commons-lang 项目中的 FastDateFormat 类,可以安全地从多个线程并行访问。

如果您想为@Past 添加对字符串的支持,您可以通过实现实现ConstraintValidator&lt;Past, String&gt; 的验证器并使用XML constraint mapping 注册来实现。但是,没有办法指定预期的格式。或者,您可以实现另一个自定义约束,例如 @PastWithFormat

【讨论】:

  • 它说编译错误。绑定不匹配:类型 DateFormat 不是类型 ConstraintValidator 的有界参数 的有效替代品
【解决方案2】:

最好尝试用 SimpleDateFormat 解析日期

boolean isValid(String date) {
   SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'_'HH:mm:ss");
   df.setLenient(false);
   try {
      df.parse(date);
   } catch (ParseException e) {
      return false;
   }
   return true;
}

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 2017-04-04
    • 2021-05-03
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 2018-10-21
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多