2013-07-09 47 views
3

我想验证日期的格式YYYY-MM-DD_hh:mm:ss验证日期 - Bean验证注解 - 与特定格式

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

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

+1

如果你碰巧使用Spring,你可以使用'@ DateTimeFormat'。 –

回答

3

@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类,它可以安全地从多个线程并行访问。

如果您想将对Strings的支持添加到@Past,您可以通过实施验证器实现ConstraintValidator<Past, String>并使用XML constraint mapping进行注册。但是,没有办法指定预期的格式。或者,您可以实施其他自定义约束,如@PastWithFormat

+0

它说编译错误..绑定不匹配:类型DateFormat不是绑定参数的有效替代者的类型ConstraintValidator DEADEND

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; 
}