java 验证日期 - Bean 验证注释 - 具有特定格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17539724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:15:40  来源:igfitidea点击:

Validating Date - Bean validation annotation - With a specific format

javadatedesign-patternsformatbean-validation

提问by Kevin Rave

I would like to validate a Date for the format YYYY-MM-DD_hh:mm:ss

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

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

If thats not possible, I would like to use @Pattern. But what is the regexfor the above format to use in @Pattern?

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

回答by Gunnar

@Pastsupports only Dateand Calendarbut not Strings, so there is no notion of a date format.

@Past仅支持DateCalendar而不是字符串,所以没有一个日期格式的概念。

You could create a custom constraint such as @DateFormatwhich ensures that a given string adheres to a given date format, with a constraint implementation like this:

您可以创建一个自定义约束,例如@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;
        }
    }
}

Note that the SimpleDateFormatinstance must not be stored in an instance variable of the validator class as it is not thread-safe. Alternatively you could use the FastDateFormatclass from the commons-lang project which safely can be accessed from several threads in parallel.

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

If you wanted to add support for Strings to @Pastyou could do so by implementing a validator implementing ConstraintValidator<Past, String>and registering using an XML constraint mapping. There would be no way to specify the expected format, though. Alternatively you could implement another custom constraint such as @PastWithFormat.

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

回答by Evgeniy Dorofeev

It's better to try and parse the date with SimpleDateFormat

最好尝试使用 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;
}