Validating Date - Bean validation annotation - With a specific format

爱⌒轻易说出口 提交于 2019-12-07 16:02:01

问题


I would like to validate a Date for the format 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 regex for the above format to use in @Pattern?


回答1:


@Past supports only Date and Calendar but not Strings, so there is no notion of a date format.

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

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 SimpleDateFormat instance must not be stored in an instance variable of the validator class as it is not thread-safe. Alternatively you could use the FastDateFormat class from the commons-lang project which safely can be accessed from several threads in parallel.

If you wanted to add support for Strings to @Past you 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.




回答2:


It's better to try and parse the date with 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;
}


来源:https://stackoverflow.com/questions/17539724/validating-date-bean-validation-annotation-with-a-specific-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!