Search code examples
javabean-validationjsr349

Can JSR-349 Bean Validation Annotations be Used to Validate Java Time Types?


Java Bean Validation 1.1 (JSR-349) defines annotations like @Future and @Past for validating temporal types, but they only work with java.util.Date and java.util.Calendar out of the box.

I'm using a field of type java.time.LocalDate and would like to mandate that it's in the future, but to do so it looks like I will have to write my own @Future annotation to support this type, which is a shame because @javax.validation.constraints.Future is semantically ideal.

Given the enhanced options now available in BV 1.1, is it possible to configure the validator to use the existing @javax.validation.constraints.Future annotation with a custom ConstraintValidator that would support the new Java time classes?

EDIT

Ideally I am looking to do this entirely in Java code without writing any XML. While the XML-based solution suggested below would be acceptable, I'd rather not use XML if I can help it.


Solution

  • Finally figured this out. Here's the Java version of a custom constraint definition.

    HibernateValidatorConfiguration conf = (HibernateValidatorConfiguration) Validation.byDefaultProvider().configure();
    conf.addConstraintDefinitionContributor((constraintDefinitionContributionBuilder) -> {
        constraintDefinitionContributionBuilder.constraint(Future.class)
                .validatedBy(MyCustomFutureConstraintValidator.class)
                .includeExistingValidators(true);
    });
    Validator validator = conf.buildValidatorFactory().getValidator();