Validating Date - Bean 验证注解 - 具有特定格式

Kev*_*ave 3 java format design-patterns date bean-validation

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

@Past //validates for a date that is present or past. But what are the formats it accepts
Run Code Online (Sandbox Code Playgroud)

如果那不可能,我想使用@Pattern. 但是regex上面的格式用于@Pattern什么?

Gun*_*nar 5

@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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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