Validating Date - Bean validation annotation - With a specific format

bean-validation, date, design-patterns, format, java

Solution

`@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`.

Problem

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`?

Original source